eh2*_*699 3 python regex filter pandas
我有一个pandas数据框,我想通过列中的特定单词(test)进行过滤.我试过了:
df[df[col].str.contains('test')]
但它返回一个只有列名的空数据帧.对于输出,我正在寻找一个包含所有包含单词'test'的行的数据帧.我能做什么?
编辑(添加样本):
data = pd.read_csv(/...csv)
数据有5个cols,包括'BusinessDescription',我想提取Business Descriptioncol 中有'dental'(不区分大小写)字样的所有行,所以我使用了:
filtered = data[data['BusinessDescription'].str.contains('dental')==True]
我得到一个空的数据帧,只有5个列的标题名称.
看来你需要的参数flags在contains:
import re
filtered = data[data['BusinessDescription'].str.contains('dental', flags = re.IGNORECASE)]
Run Code Online (Sandbox Code Playgroud)
另一个解决方案,感谢Anton vBR首先转换为小写:
filtered = data[data['BusinessDescription'].str.lower().str.contains('dental')]
Run Code Online (Sandbox Code Playgroud)
示例:
对于将来的编程,我建议在引用数据帧时使用关键字df而不是数据.使用该表示法是围绕SO的常用方法.
import pandas as pd
data = dict(BusinessDescription=['dental fluss','DENTAL','Dentist'])
df = pd.DataFrame(data)
df[df['BusinessDescription'].str.lower().str.contains('dental')]
BusinessDescription
0 dental fluss
1 DENTAL
Run Code Online (Sandbox Code Playgroud)
时间:
d = dict(BusinessDescription=['dental fluss','DENTAL','Dentist'])
data = pd.DataFrame(d)
data = pd.concat([data]*10000).reset_index(drop=True)
#print (data)
In [122]: %timeit data[data['BusinessDescription'].str.contains('dental', flags = re.IGNORECASE)]
10 loops, best of 3: 28.9 ms per loop
In [123]: %timeit data[data['BusinessDescription'].str.lower().str.contains('dental')]
10 loops, best of 3: 32.6 ms per loop
Run Code Online (Sandbox Code Playgroud)
警告:
性能实际上取决于数据 - DataFrame匹配条件的值的大小和数量.