我正在努力清理 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.
请您参考如下方法:
使用str.findall与 Series.str.join将列表的值与由 | 正则表达式 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
如果需要 NaN 而不是空字符串,请使用 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
