gpt4 book ai didi

python - 在 pandas 中使用正则表达式验证字符串

转载 作者:太空宇宙 更新时间:2023-11-03 15:00:14 24 4
gpt4 key购买 nike

我需要一些帮助。

我对 Python 还很陌生(我使用与 Anaconda 捆绑在一起的版本 3.0),并且我想使用正则表达式来验证/返回仅包含与条件匹配的有效数字的列表(例如\d{11} 表示 11 位数字) 。我正在使用 Pandas 获取列表

df = pd.DataFrame(columns=['phoneNumber','count'], data=[
['08034303939',11],
['08034382919',11],
['0802329292',10],
['09039292921',11]])

当我使用

退回所有商品时
for row in df.iterrows(): # dataframe.iterrows() returns tuple
print(row[1][0])

它返回所有没有正则表达式验证的项目,但是当我尝试用它进行验证时

for row in df.iterrows(): # dataframe.iterrows() returns tuple
print(re.compile(r"\d{11}").search(row[1][0]).group())

它返回一个属性错误(因为不匹配值的返回值为 None。

我该如何解决这个问题,或者有更简单的方法吗?

最佳答案

如果要验证,可以使用str.match并使用 df.astype(bool) 转换为 bool 掩码:

x = df['phoneNumber'].str.match(r'\d{11}').astype(bool)
x

0 True
1 True
2 False
3 True
Name: phoneNumber, dtype: bool

您可以使用 bool 索引仅返回包含有效电话号码的行。

df[x]

phoneNumber count
0 08034303939 11
1 08034382919 11
3 09039292921 11

关于python - 在 pandas 中使用正则表达式验证字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45174613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com