我有一个df列,看起来像这样:
col1
Non Profit
Other-501c3
501c3
Sole Proprietor
我如何创建字典对象或映射层(对所有建议均开放),如果它符合条件并更改了键值,则可以在其中传递任何值?
例如,如果将值Other-501c3
更改为non-profit
。
示例(等号之后的所有内容都需要更改为等号之前的值):
1. non-profit = (Non Profit, Other-501c3, 501c3,NON-Profit, Not-for-profit).
2. Sole Proprietor = (Sole Proprietor,Sole Proprietorship)
解决方案应该是可扩展的,我可以添加更多的“键值”对
先感谢您。
从key
s创建字典,将它们合并并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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句