python - 逐行将整个 Pandas 数据框格式化为字符串

标签 python pandas dataframe

我有一个 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/

相关文章:

python - 使用 flask-wtf 和 flask-bootstrap 时如何将 html 属性传递给 wtf.form_field

python - 在 TensorFlow 中使用图像批处理进行多次运行

python - 相当于 pandas 中的 fct_lump

python - 数据框将文本拆分为新列

python - 如何让 PyC​​harm 在输出控制台中显示整个数据帧?

Python程序根据给定值添加小数点

python - 删除 unicode 字符

python - 在 Pandas 中使用多重索引过滤数据帧

python - Pandas:在数据框中搜索星号时出错。例如:busiest_hosts ['host'].str.contains ('***.botol.dk')

python - Pandas DataFrame.update() 函数中的 `overwrite` 参数有什么作用?