小能豆

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

py

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

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'"

可以这样做吗?如何做?


阅读 71

收藏
2025-02-26

共1个答案

小能豆

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

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