Pandas:添加一个基于其他列的df列,其中多个值Map到同一个新列值

chhkpiq4  于 2022-11-27  发布在  其他
关注(0)|答案(3)|浏览(140)

我有一个 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'

如何将catdog合并为animal

df1.loc[df1['col1'] == 'cat' | df1['col1'] == 'dog','col2'] = 'animal'
kqlmhetl

kqlmhetl1#

构建您的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
sbdsn5lh

sbdsn5lh2#

由于多个条目可能属于一个类别,我建议您从字典开始将类别Map到条目:

cat_item = {'animal': ['cat', 'dog'], 'color': ['green', 'blue']}

您可能会发现这更容易维护。* 然后 * 使用字典解析反转您的字典,后跟pd.Series.map

item_cat = {w: k for k, v in cat_item.items() for w in v}

df1['col2'] = df1['col1'].map(item_cat)

print(df1)

    col1    col2
0    cat  animal
1    cat  animal
2    dog  animal
3  green   color
4   blue   color

您也可以使用pd.Series.replace,但通常是less efficient

pb3s4cty

pb3s4cty3#

您也可以尝试使用np.select,如下所示:

options = [(df1.col1.str.contains('cat|dog')), 
           (df1.col1.str.contains('green|blue'))]

settings = ['animal', 'color']

df1['setting'] = np.select(options,settings)

我发现,即使是非常大的 Dataframe ,它也能非常快地工作

相关问题