首页 > 解决方案 > 使用字符串匹配填充新的数据框列

问题描述

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

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

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 行,我的可能颜色列表是几十个项目。

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

标签: pythonpandas

解决方案


这是一种方法:

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

推荐阅读