如何将键映射到多个值到数据帧列?

2024-09-27 07:29:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个df列是这样的:

col1
Non Profit
Other-501c3
501c3
Sole Proprietor

如何创建一个dictionary对象或映射层(对所有建议开放),如果任何值与条件匹配并对键值进行更改,我可以在其中传递该值?在

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

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

^{pr2}$

解决方案应该是可伸缩的我可以添加更多的“键值”对

提前谢谢你。在


Tags: 对象示例dfdictionary条件建议col1键值
2条回答

类似于@jezrael's的解决方案,但是可以使用^{}代替创建新字典:

from collections import ChainMap

# dataframe setup
df = pd.DataFrame({'col1': ['Non Profit', 'Other-501c3', '501c3', 'Sole Proprietor']})

# create ChainMap
L1 = ['Non Profit', 'Other-501c3', '501c3','NON-Profit', 'Not-for-profit']
L2 = ['Sole Proprietor','Sole Proprietorship']
d = ChainMap(dict.fromkeys(L1, 'non-profit'), dict.fromkeys(L2, 'Sole Proprietor'))

# map values
df['new'] = df['col1'].map(d.get)

print(df)

              col1              new
0       Non Profit       non-profit
1      Other-501c3       non-profit
2            501c3       non-profit
3  Sole Proprietor  Sole Proprietor

keys创建字典,合并它们并^{}

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

相关问题 更多 >

    热门问题