Jar*_*rad 3 python formatting dictionary dataframe pandas
问题设置
import pandas as pd
df = pd.DataFrame(data={'Currency': {0: 111.23, 1: 321.23},
'Int': {0: 23, 1: 3},
'Rate': {0: 0.03030, 1: 0.09840}}
)
Run Code Online (Sandbox Code Playgroud)
生成以下DataFrame
Currency Int Rate
0 111.23 23 0.0303
1 321.23 3 0.0984
Run Code Online (Sandbox Code Playgroud)
我想使用如下所示的dict将非常特定的格式应用于数据框中的每一列:
format_mapping={'Currency': '${:,.2f}', 'Int': '{:,.0f}', 'Rate': '{:.2f}%'}
Run Code Online (Sandbox Code Playgroud)
我知道我可以将applymap用于多列或应用于单个列:
#All columns
df = df.applymap('{:.2f}%'.format)
#Specific columns
df['Rate'] = df['Rate'].apply('{:.2f}%'.format)
Run Code Online (Sandbox Code Playgroud)
题
我怎样才能通过每一列的数据帧进行迭代,并使用字典在应用格式dict key是column和value是string格式化?
最终结果看起来像这样(忽略百分比现在不再乘以100的事实)
Currency Int Rate
0 $111.23 23 0.03%
1 $321.23 3 0.10%
Run Code Online (Sandbox Code Playgroud)
Ste*_*EOX 18
2021 年(Pandas 1.2.3)您可以使用df.style.format():
import pandas as pd
df = pd.DataFrame(
data={
"Currency": {0: 111.23, 1: 321.23},
"Int": {0: 23, 1: 3},
"Rate": {0: 0.03030, 1: 0.09840},
}
)
format_mapping = {"Currency": "${:,.2f}", "Int": "{:,.0f}", "Rate": "{:.2f}%"}
df.style.format(format_mapping)
Run Code Online (Sandbox Code Playgroud)
更多信息:https://pandas.pydata.org/pandas-docs/stable/user_guide/style.html#Finer-Control: -Display-Values
最简单的方法是迭代format_mapping字典,然后在列(由键表示)上应用由表示的格式value.示例 -
for key, value in format_mapping.items():
df[key] = df[key].apply(value.format)
Run Code Online (Sandbox Code Playgroud)
演示 -
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%
Run Code Online (Sandbox Code Playgroud)