使用Dict映射将格式化应用于数据框中的每一列 [英] Apply Formatting to Each Column in Dataframe Using a Dict Mapping

查看:46
本文介绍了使用Dict映射将格式化应用于数据框中的每一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题设置

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

产生以下DataFrame

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}%'}

我知道我可以对多个列使用applymap或对单个列应用:

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

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

问题

如何遍历数据帧中的每一列并使用字典应用格式,其中 dict key column value string 格式吗?

How can I iterate through each column in a dataframe and apply formatting using a dictionary where the dict key is the column and the value is the string formatting?

最终结果将如下所示(忽略当前百分比未乘以100的事实)

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

  Currency Int   Rate
0  $111.23  23  0.03%
1  $321.23   3  0.10%

推荐答案

最简单的方法是遍历 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%

这篇关于使用Dict映射将格式化应用于数据框中的每一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆