我有一个熊猫数据框,我想以特殊格式打印出来:
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
轻松完成。还有更好的方法吗?
答案 0 :(得分:2)
您可以使用apply
axis=1
format
并使用适当的格式字符串。确保在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