【问题标题】:Use string matching to populate new dataframe column [duplicate]使用字符串匹配填充新的数据框列[重复]
【发布时间】:2019-03-13 22:39:24
【问题描述】:

我正在尝试根据该行中的另一列是否包含字符串来填充熊猫数据框中的新列。

例如,我有一个可能的颜色列表:

possible_colors = ['red', 'blue', 'green', orange', 'purple']

数据框包含假设产品的销售数据。产品名称在其产品代码中包含一种颜色,我将创建一个列将该产品标记为其正确颜色。

df = {'product': ['123red309','20424green098','2purple09183'],
          'sales_qty': [20, 5, 10]}

如果产品列包含字符串“green”,我想用字符串“green”填充新列 Color。

我尝试使用代码这样做:

for color in possible_colors:
    df['Color'] = np.where(df.product.str.contains(color),color)

这给了我警告ValueError: either both or neither of x and y should be given

我的实际数据框当然是数千行,而不仅仅是 3 行,我的可能颜色列表是几十个项目。

如何正确完成任务?谢谢!

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你可以使用series.str.extract():

    df['color']=df['product'].str.extract(r'({})'.format('|'.join(possible_colors)))
    print(df)
    
             product  sales_qty   color
    0      123red309         20     red
    1  20424green098          5   green
    2   2purple09183         10  purple
    

    在哪里:r'({})'.format('|'.join(possible_colors)) 产量:'(red|blue|green|orange|purple)'

    【讨论】:

      【解决方案2】:

      这是一种方法:

      df['color'] = df['product'].apply(lambda x: ''.join(i for i in possible_colors 
                                                          if i in x) or None)
      
             product     sales_qty   color
      0      123red309         20     red
      1  20424green098          5   green
      2   2purple09183         10  purple
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-08
        • 1970-01-01
        • 2020-04-29
        • 2017-02-10
        • 2016-10-18
        • 1970-01-01
        • 2011-05-27
        相关资源
        最近更新 更多