簡體   English   中英

從正在檢查列表的字符串 findall output 中刪除方括號

[英]Remove square brackets from string findall output that is checking a list

我有一個看起來像這樣的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 

我正在使用以下代碼查看列中包含的項目是否包含在列表中:

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))

這給了我一個看起來像這樣的新列:

   Items                                                 Item_list
0  Product A + Product B + Product C                     [Product C]
1  Product A + Product B + Product B1 + Product C1       [Product B1]

有誰知道我怎樣才能讓項目列表只給我我正在搜索的項目而沒有 [] 括號?

所需的 output 如下:

   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 解決方案,它給了我我想要的 output 但完成時間太長了,真正的數據源非常大!

任何幫助/指導將不勝感激!

親切的問候

只需將.apply(','.join)添加到您的findall命令中,如下所示:

df['Item_list'] = df.Items.str.findall('|'.join(My_Items)).apply(','.join)                                                                                                                        

Output:

                                             Items             Item_list
0                Product A + Product B + Product C             Product C
1  Product A + Product B + Product B1 + Product C1             Product B1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM