我有一个这样的数据框:
df1 = pd.DataFrame({'col1' : ['cat', 'cat', 'dog', 'green', 'blue']})
我想要一个提供该类别的新列,如下所示:
dfoutput = pd.DataFrame({'col1' : ['cat', 'cat', 'dog', 'green', 'blue'],
'col2' : ['animal', 'animal', 'animal', 'color', 'color']})
我知道我可以使用.loc
以下方法低效地进行操作:
df1.loc[df1['col1'] == 'cat','col2'] = 'animal'
df1.loc[df1['col1'] == 'dog','col2'] = 'animal'
我该如何结合cat
并dog
同时做到animal
?这不起作用:
df1.loc[df1['col1'] == 'cat' | df1['col1'] == 'dog','col2'] = 'animal'
建立你的dict
事map
d={'dog':'ani','cat':'ani','green':'color','blue':'color'}
df1['col2']=df1.col1.map(d)
df1
col1 col2
0 cat ani
1 cat ani
2 dog ani
3 green color
4 blue color
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句