Python Pandas 使用字典映射将格式应用于数据帧中的每一列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32744997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:55:21  来源:igfitidea点击:

Python Pandas Apply Formatting to Each Column in Dataframe Using a Dict Mapping

pythondictionarypandasformattingdataframe

提问by Jarad

Problem Setup

问题设置

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}}
            )

Produces the following DataFrame

产生以下数据帧

   Currency  Int    Rate
0    111.23   23  0.0303
1    321.23    3  0.0984

I want to apply very specific formatting to each column in the dataframe using a dict like the following:

我想使用如下所示的字典对数据框中的每一列应用非常具体的格式:

format_mapping={'Currency': '${:,.2f}', 'Int': '{:,.0f}', 'Rate': '{:.2f}%'}

I know I can use applymap for multiple columns or apply on a single column:

我知道我可以将 applymap 用于多列或应用于单列:

#All columns
df = df.applymap('{:.2f}%'.format)
#Specific columns
df['Rate'] = df['Rate'].apply('{:.2f}%'.format)

Question

How can I iterate through each column in a dataframe and apply formatting using a dictionary where the dictkeyis the columnand the valueis the stringformatting?

如何遍历数据框中的每一列并使用字典应用格式,其中dictkeyis thecolumn和 the valueisstring格式?

End result would look like this (ignore the fact that percent wasn't multiplied by 100 for now)

最终结果看起来像这样(暂时忽略百分比没有乘以 100 的事实)

  Currency Int   Rate
0  1.23  23  0.03%
1  1.23   3  0.10%

回答by Anand S Kumar

The easiest way would be to iterate through the format_mappingdictionary and then apply on the column (denoted by the key) the formatting denoted by the value. Example -

最简单的方法是遍历format_mapping字典,然后将value. 例子 -

for key, value in format_mapping.items():
    df[key] = df[key].apply(value.format)

Demo -

演示 -

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  1.23  23  0.03%
1  1.23   3  0.10%