如何将键映射到多个值到dataframe列? [英] How to map key to multiple values to dataframe column?

查看:93
本文介绍了如何将键映射到多个值到dataframe列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个df列,如下所示:

I have a df column that looks like this:

col1
Non Profit
Other-501c3
501c3
Sole Proprietor

如何创建字典对象或映射层(向所有建议开放),如果它匹配标准并更改了键值,则可以在其中传递任何值?

How can I create a dictionary object or mapping layer(open to all suggestions) where I can pass any value if it matches criteria and changes to the key value?

例如,如果值是Other-501c3,则将其更改为non-profit.

For example if the value is Other-501c3 then change it to non-profit.

示例(等号之后的所有内容都需要更改为等号之前的值):

Examples (everything after the equal sign needs to change to the value before equal sign):

1. non-profit = (Non Profit, Other-501c3, 501c3,NON-Profit, Not-for-profit).

2. Sole Proprietor = (Sole Proprietor,Sole Proprietorship)

该解决方案应该具有可扩展性,我可以添加更多的键值"对

The solution should be scalable I can add in more 'key value' pairs

先谢谢您.

推荐答案

key s创建字典,将其合并并

Create dictionaries from keys, merge them and map:

L1 = ['Non Profit', 'Other-501c3', '501c3','NON-Profit', 'Not-for-profit']
d1 = dict.fromkeys(L1, 'non-profit')

L2 = ['Sole Proprietor','Sole Proprietorship']
d2 = dict.fromkeys(L2, 'Sole Proprietor')

d = {**d1, **d2}
print (d)
{'Non Profit': 'non-profit', 
 'Other-501c3': 'non-profit', 
 '501c3': 'non-profit',
 'NON-Profit': 'non-profit', 
 'Not-for-profit': 'non-profit', 
 'Sole Proprietor': 'Sole Proprietor',
 'Sole Proprietorship': 'Sole Proprietor'}

df['new'] = df['col1'].map(d)
print (df)
              col1              new
0       Non Profit       non-profit
1      Other-501c3       non-profit
2            501c3       non-profit
3  Sole Proprietor  Sole Proprietor

这篇关于如何将键映射到多个值到dataframe列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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