首页 > 解决方案 > 在 Pandas 列中搜索列表元素,如果匹配,则将元素返回到新列

问题描述

我正在努力清理 pandas DataFrame 列。该列包含我想从列表中查找和提取的单词。

下面是我所拥有的。但它不会返回多个匹配项。下面是一个例子。

data = {'A':['abc 1 foo','def 1,bar','abc 2','def 2', 'abc 1/def 1 baz', 'abc 1,def 1']}
l = ['abc 1', 'def 1']

df = pd.DataFrame(data)

for idx, row in df.iterrows():
    for x in l:
        if x in row.A:
            df.loc[idx, 'new_col'] = x```

Actual output:

A            new_col
abc 1            abc 1
def 1            def 1
abc 2            NaN
def 2            NaN
abc 1/def 1      def 1
abc 1,def 1      def 1

Expected output:

A            new_col
abc 1            abc 1
def 1            def 1
abc 2            NaN
def 2            NaN
abc 1/def 1      abc 1,def 1
abc 1,def 1      abc 1,def 1

Note: the seperator in col A could be anything('/', ';') but seperator in new_col should be fixed.

标签: pythonpandas

解决方案


str.findallSeries.str.joinlist 的连接值一起使用,|用于正则表达式OR\b单词边界:

pat = '|'.join(r"\b{}\b".format(x) for x in l)
df['new_col'] = df['A'].str.findall(pat).str.join(',')
print (df)
                 A      new_col
0        abc 1 foo        abc 1
1        def 1,bar        def 1
2            abc 2             
3            def 2             
4  abc 1/def 1 baz  abc 1,def 1
5      abc 1,def 1  abc 1,def 1

如果需要NaNs 而不是空字符串,请使用numpy.where

pat = '|'.join(r"\b{}\b".format(x) for x in l)
s = df['A'].str.findall(pat)
df['new_col'] = np.where(s.astype(bool), s.str.join(','), np.nan)
print (df)
                 A      new_col
0        abc 1 foo        abc 1
1        def 1,bar        def 1
2            abc 2          NaN
3            def 2          NaN
4  abc 1/def 1 baz  abc 1,def 1
5      abc 1,def 1  abc 1,def 1

推荐阅读