pandas数据帧字符串格式化(访问给定列)

时间:2016-02-25 16:02:12

标签: python string pandas formatting string-formatting

我尝试使用新式格式来显示给定/指定列的条目:

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

但我想这样做:

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

是否可以这样做以及如何做到?

2 个答案:

答案 0 :(得分:2)

我认为您可以删除''中的one['a']

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

答案 1 :(得分:1)

您可以使用loc获取列a的值。

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

您也可以这样做。

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'