python - 无法使用正则表达式查找 pandas 中值集的子字符串的第一次出现

标签 python python-3.x pandas substring findall

我有一个如下数据框,我只需要查找字符串中第一次出现的值集。

我无法将“查找”功能与正则表达式和字典一起使用。如果我使用“findall”函数,它当然会找到所有出现的情况,这不是我需要的。

Text

51000/1-PLASTIC 150 Prange
51034/2-RUBBER KL 100 AA
51556/3-PAPER BD+CM 1 BOXT2
52345/1-FLOW IJ 10place 500 plastic
54975/1-DIVIDER PQR 100 BC
54975/1-SCALE DEF 555 AB Apple 
54975/1-PLASTIC ABC 4.6 BB plastic  

代码:

import re

L = ['PLASTIC','RUBBER','PAPER','FLOW']
pat = '|'.join(r"\b{}\b".format(x) for x in L)

df['Result'] = df['Text'].str.find(pat, flags=re.I).str.join(' ')
print(df)

df = df.replace(r'^\s*$', np.nan, regex=True)
df = df.replace(np.nan, "Not known", regex=True)
#df['Result'] = df['Result'].str.lower()

预期结果:

Text                                                   Result

51000/1-PLASTIC 150 Prange                            Plastic
51034/2-RUBBER KL 100 AA                              Rubber
51556/3-PAPER BD+CM 1 BOXT2                           Paper
52345/1-FLOW IJ 10place 500 plastic                   Flow
54975/1-DIVIDER PQR 100 BC                            Not known
54975/1-SCALE DEF 555 AB Apple                        Not KNown 
54975/1-PLASTIC ABC 4.6 BB plastic                    Plastic

错误:

TypeError: find() got an unexpected keyword argument 'flags'

最佳答案

使用Series.str.findall而是通过索引 str[0] 选择 findall 返回的列表的第一个值来查找 find:

import re

L = ['PLASTIC','RUBBER','PAPER','FLOW']
pat = '|'.join(r"\b{}\b".format(x) for x in L)

df['Result'] = df['Text'].str.findall(pat, flags=re.I).str[0]

或者使用Series.str.extract :

df['Result'] = df['Text'].str.extract('(' + pat + ')', flags=re.I)
<小时/>

然后将缺失值转换为未知:

df['Result'] = df['Result'].fillna("Not known")

最后如有必要请使用 Series.str.capitalize :

df['Result'] = df['Result'].str.capitalize()
print (df)
                                   Text     Result
0            51000/1-PLASTIC 150 Prange    Plastic
1              51034/2-RUBBER KL 100 AA     Rubber
2           51556/3-PAPER BD+CM 1 BOXT2      Paper
3   52345/1-FLOW IJ 10place 500 plastic       Flow
4            54975/1-DIVIDER PQR 100 BC  Not known
5        54975/1-SCALE DEF 555 AB Apple  Not known
6  54975/1-PLASTIC ABC 4.6 BB plastic      Plastic

关于python - 无法使用正则表达式查找 pandas 中值集的子字符串的第一次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58057186/

相关文章:

python-3.x - 向外部服务器发出 POST 请求时出现 SSL 证书错误

python - 如何使用 iloc[] 选择 pandas 数据框的倒数第二行?

python - assertRaises 无法捕获错误

python - 在 struct.unpack 格式字符串中间切换字节序

python - 在截取屏幕截图的脚本中出现错误, undefined variable

python-3.x - 如何使用 python 脚本在 GCP 中创建 DNS 记录集

python - pandas xs 函数的多列选择失败

pandas - 当日期介于两个日期之间时合并 Pandas

python - Django Rest 框架 JWT

python - Matplotlib:绘制具有数据坐标中给定宽度的线