Ame*_*_90 1 python dataframe pandas
我有一个看起来像这样的 df:
import pandas as pd
import numpy as np
print(df)
Items
0 Product A + Product B + Product C
1 Product A + Product B + Product B1 + Product C1
Run Code Online (Sandbox Code Playgroud)
我使用以下代码来查看列中包含的项目是否包含在列表中:
My_Items = ['Product B1', 'Product C']
Item_mask = df.Items.str.findall('|'.join(My_Items )).str.len()
df['Item_list'] = df.Items.str.findall('|'.join(My_Items))
Run Code Online (Sandbox Code Playgroud)
这给了我一个新的专栏,如下所示:
Items Item_list
0 Product A + Product B + Product C [Product C]
1 Product A + Product B + Product B1 + Product C1 [Product B1]
Run Code Online (Sandbox Code Playgroud)
有谁知道如何获取项目列表以提供我正在搜索的项目而不使用 [] 括号?
所需的输出如下:
Items Item_list
0 Product A + Product B + Product C Product C
1 Product A + Product B + Product B1 + Product C1 Product B1
Run Code Online (Sandbox Code Playgroud)
我尝试使用以下方法将其转换为字符串:
df['Item_list'] = df.Items.str.findall('|'.join(My_Items)).astype(str)
Run Code Online (Sandbox Code Playgroud)
但这给了我这样的数据,例如['Product C'],这也不是我想要的。
我还尝试了 iterrows 解决方案,它给了我想要的输出,但需要很长时间才能完成,真正的数据源非常大!
任何帮助/指导将不胜感激!
亲切的问候
只需添加.apply(','.join)到您的findall命令中,如下所示:
df['Item_list'] = df.Items.str.findall('|'.join(My_Items)).apply(','.join)
Run Code Online (Sandbox Code Playgroud)
输出:
Items Item_list
0 Product A + Product B + Product C Product C
1 Product A + Product B + Product B1 + Product C1 Product B1
Run Code Online (Sandbox Code Playgroud)