pandas dataframe string formatting (access a given

2019-08-13 02:42发布

问题:

I try to use new-style formatting to display the entry at a given/specified column:

np.random.seed(1234)
df = pd.DataFrame(np.random.randint(7, size=(2, 2)), columns=['a', 'b'])
c = df.iloc[0, :] # get row number 0
print("Here is {one[0]} and {two}".format(one=c, two=c['b'])) # Ok

But I'd like to do it as follows:

print("Here is {one['a']} and {two}".format(one=c, two=c['b'])) ## Unfortunately KeyError: "'a'"

Is it possible to do that and how?

回答1:

I think you can remove '' in one['a']:

print("Here is {one[a]} and {two}".format(one=c, two=c['b']))
Here is 3 and 6


回答2:

You can use loc to get the value of column a.

print("Here is {one} and {two}".format(one=c.loc['a'], two=c['b']))
Here is 3 and 6

You can also do it this way.

df['sum'] = df.sum(axis=1)

n = 0  # Get the first row.    
>>> "{row[a]} and {row[b]} makes {row[sum]}".format(row=df.iloc[n, :])
'3 and 6 makes 9'