我有一个 Pandas 数据框,我想用一种特殊格式打印出来:
df = pd.DataFrame({'A': [1, 5, 3], 'B': [90, 74, 180], 'C': ["aabb","bbcc", "ccdd"]})
所需的输出是:
For x1, referenced by aabb, the address is 0x5a
For x5, referenced by bbcc, the address is 0x4a
For x3, referenced by aabb, the address is 0xb4
即像-
print('For x%i, referenced by %s, the address is %x' % (df.A, df.C, df.B)`
将列连接为字符串不起作用 -
print('For' + df.A + df.C + df.B)
我可以使用 iterrows
轻松完成。有没有更好的办法?
最佳答案
您可以使用带有适当格式字符串的format
沿axis=1
应用
。确保在 lambda 中使用字典解包来完成它。
sfmt = 'For x{A}, referenced by {C}, the address is {B:#04x}'.format
df.apply(lambda x: sfmt(**x), 1)
0 For x1, referenced by aabb, the address is 0x5a
1 For x5, referenced by bbcc, the address is 0x4a
2 For x3, referenced by ccdd, the address is 0xb4
dtype: object
关于python - 逐行将整个 Pandas 数据框格式化为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45136733/