Python 从正在检查列表的字符串findall输出中删除方括号
我有一个df,看起来像这样:Python 从正在检查列表的字符串findall输出中删除方括号,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个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 Items Item_
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
Items Item_list
0 Product A + Product B + Product C [Product C]
1 Product A + Product B + Product B1 + Product C1 [Product B1]
df['Item_list'] = df.Items.str.findall('|'.join(My_Items)).apply(','.join)
我使用以下代码查看列中包含的项目是否包含在列表中:
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))
这给了我一个新的专栏,如下所示:
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
Items Item_list
0 Product A + Product B + Product C [Product C]
1 Product A + Product B + Product B1 + Product C1 [Product B1]
df['Item_list'] = df.Items.str.findall('|'.join(My_Items)).apply(','.join)
有人知道我如何让项目列表只提供我正在搜索的项目,而不使用[]括号吗
所需输出如下:
Items Item_list
0 Product A + Product B + Product C Product C
1 Product A + Product B + Product B1 + Product C1 Product B1
我已尝试使用以下方法将其转换为字符串:
df['Item_list'] = df.Items.str.findall('|'.join(My_Items)).astype(str)
但这给了我这样的数据,例如['Product C'],这也不是我想要的
我还尝试了一个iterrows解决方案,它为我提供了所需的输出,但它需要太长的时间才能完成,真正的数据源非常大
任何帮助/指导都将不胜感激
亲切问候只需将添加到命令中。将(','.join)
应用到findall
命令中,如下所示:
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
Items Item_list
0 Product A + Product B + Product C [Product C]
1 Product A + Product B + Product B1 + Product C1 [Product B1]
df['Item_list'] = df.Items.str.findall('|'.join(My_Items)).apply(','.join)
输出:
Items Item_list
0 Product A + Product B + Product C Product C
1 Product A + Product B + Product B1 + Product C1 Product B1
您不能将[0]
传递给您的df['Item\u list']
?括号是列表符号。如果只想在其中包含字符串,则不要在ll处使用列表,或者使用下标访问所需的列表位置。