pandas dataframe string formatting (access a given column)

依然范特西╮ 提交于 2019-12-13 01:53:16

问题


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'


来源:https://stackoverflow.com/questions/35632328/pandas-dataframe-string-formatting-access-a-given-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!