【发布时间】: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 行,我的可能颜色列表是几十个项目。
如何正确完成任务?谢谢!
【问题讨论】: