更新时间:2022-12-12 23:27:56
最简单的方法是遍历format_mapping
字典,然后将value
表示的格式应用于列(由键表示) .示例-
The easiest way would be to iterate through the format_mapping
dictionary and then apply on the column (denoted by the key) the formatting denoted by the value
. Example -
for key, value in format_mapping.items():
df[key] = df[key].apply(value.format)
演示-
In [62]: df = pd.DataFrame(data={'Currency': {0: 111.23, 1: 321.23},
....: 'Int': {0: 23, 1: 3},
....: 'Rate': {0: 0.03030, 1: 0.09840}}
....: )
In [63]:
In [63]: format_mapping={'Currency': '${:,.2f}', 'Int': '{:,.0f}', 'Rate': '{:.2f}%'}
In [64]: for key, value in format_mapping.items():
....: df[key] = df[key].apply(value.format)
....:
In [65]: df
Out[65]:
Currency Int Rate
0 $111.23 23 0.03%
1 $321.23 3 0.10%