python - 使用正则表达式选择数据

标签 python regex pandas

我有这样一个数据框

import pandas as pd

df = pd.DataFrame({'a': ['abc', 'r00001', 'r00010', 'rfoo', 'r01234', 'r1234'], 'b': range(6)})

        a  b
0     abc  0
1  r00001  1
2  r00010  2
3    rfoo  3
4  r01234  4
5   r1234  5

我现在想选择此数据框的所有列,其中 a 列中的条目以 r 开头,后跟五个数字。

From here我了解了如果仅以 r 开头而没有数字,人们将如何做到这一点:

print df.loc[df['a'].str.startswith('r'), :]

        a  b
1  r00001  1
2  r00010  2
3    rfoo  3
4  r01234  4
5   r1234  5

像这样

print df.loc[df['a'].str.startswith(r'[r]\d{5}'), :]

当然不行。如何正确地做到这一点?

最佳答案

选项 1
pd.Series.str.match

df.a.str.match('^r\d{5}$')

1     True
2     True
3    False
4     True
5    False
Name: a, dtype: bool

将其用作过滤器

df[df.a.str.match('^r\d{5}$')]

        a  b
1  r00001  1
2  r00010  2
4  r01234  4

选项 2
使用字符串方法自定义列表理解

f = lambda s: s.startswith('r') and (len(s) == 6) and s[1:].isdigit()
[f(s) for s in df.a.values.tolist()]

[False, True, True, False, True, False]

将其用作过滤器

df[[f(s) for s in df.a.values.tolist()]]

        a  b
1  r00001  1
2  r00010  2
4  r01234  4

时间

df = pd.concat([df] * 10000, ignore_index=True)

%timeit df[[s.startswith('r') and (len(s) == 6) and s[1:].isdigit() for s in df.a.values.tolist()]]
%timeit df[df.a.str.match('^r\d{5}$')]
%timeit df[df.a.str.contains('^r\d{5}$')]

10 loops, best of 3: 22.8 ms per loop
10 loops, best of 3: 33.8 ms per loop
10 loops, best of 3: 34.8 ms per loop

关于python - 使用正则表达式选择数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44953069/

相关文章:

python - 在oracle SQL*PLUS中执行Python脚本

python - 如何让 Python 求解这个二阶非线性 ODE?

python - 如何在 A 星算法中添加更多的起点和目标点?

python - Numpy选择返回 bool 错误消息

python - Pandas 数据框的组内计算

python - 相同的字符串在 python 中不匹配 - 空格问题(前导/尾随空格已删除)

python - 如何使用 pandas 快速将数据框中的字符串更改为整数 ID?

java - 用带有特殊字符的字符串进行分割

ruby - 字符串:用数字替换空格

python - 通过Python解析 'ip addr'的输出