我有一个 Dataframe ,如下所示:
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'
3条答案
按热度按时间kqlmhetl1#
构建您的
dict
,然后执行map
sbdsn5lh2#
由于多个条目可能属于一个类别,我建议您从字典开始将类别Map到条目:
您可能会发现这更容易维护。* 然后 * 使用字典解析反转您的字典,后跟
pd.Series.map
:您也可以使用
pd.Series.replace
,但通常是less efficient。pb3s4cty3#
您也可以尝试使用np.select,如下所示:
我发现,即使是非常大的 Dataframe ,它也能非常快地工作