【问题标题】:Pandas: Adding a df column based on other column with multiple values map to the same new column valuePandas:添加基于具有多个值的其他列的 df 列映射到相同的新列值
【发布时间】:2019-05-30 14:30:49
【问题描述】:

我有一个这样的数据框:

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'

【问题讨论】:

    标签: python pandas dictionary series


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-19
        • 2022-11-18
        • 2019-01-10
        相关资源
        最近更新 更多