python - 在 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.
解决方案
str.findall
与Series.str.join
list 的连接值一起使用,|
用于正则表达式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
s 而不是空字符串,请使用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
推荐阅读
- html - css3动画弹跳字母的问题
- c - makefile - 没有规则来制作目标 c
- nginx - Rails 6 Production - Webpacker 在 manifest.json 中找不到样式
- c# - 为什么要将变量声明为以类命名的类型
- c - 我想优化这个程序
- rest - 删除重复请求方法检查代码的惯用方法
- java - 为什么CMS Final Remark中的ParNew,而sys时间那么长?
- android - Android - Exoplayer 2 - 平滑地改变重叠的音乐
- python - PyCharm 在设置解释器时出错:没有这样的选项:--python
- javascript - jQuery 选择器不适用于数据表