我有这样一个数据框
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/