我尝试使用新式格式来显示给定/指定列的条目:
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'"
是否可以这样做以及如何做到?
答案 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'