繁体   English   中英

Pandas:将基于具有多个值 map 的其他列的 df 列添加到相同的新列值

[英]Pandas: Adding a df column based on other column with multiple values map to the same new column value

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

建立你的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

由于多个项目可能属于单个类别,我建议您从将类别映射到项目的字典开始:

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 ,但这通常效率较低

您也可以像这样尝试使用 np.select:

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

settings = ['animal', 'color']

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

我发现即使使用非常大的数据帧,它也能非常快速地工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM