python - 使用字符串匹配填充新的数据框列
问题描述
我正在尝试根据该行中的另一列是否包含字符串来填充熊猫数据框中的新列。
例如,我有一个可能的颜色列表:
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 行,我的可能颜色列表是几十个项目。
如何正确完成任务?谢谢!
解决方案
这是一种方法:
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
推荐阅读
- javascript - 我如何有多个类来监听 Javascript 中的点击事件?
- flare - 如何将 Flare 构建的在线帮助挂接到 Web 应用程序中?
- node.js - 如何在 webpack 中包含 readline
- android - 在 kotlin 中使用改造解析 JSON 对象
- docker - 在 Windows 10 中无法使用容器 IP 地址访问应用程序
- r - 在生存 ctree 图中调整终端面板中的 yscale
- vim - 在 Vim 中重新打开文件后重做
- python-sphinx - Spix 中的分层文档
- html - 编码字符在 HTML 上显示正常,但在 SVG 上显示
- automation - 是否可以使用第三方自动化 Visio?