Aer*_*rin 5 python dataframe pandas
我正在搜索400万行数据框中的一个子字符串或多个子字符串。
df[df.col.str.contains('Donald',case=True,na=False)]
Run Code Online (Sandbox Code Playgroud)
要么
df[df.col.str.contains('Donald|Trump|Dump',case=True,na=False)]
Run Code Online (Sandbox Code Playgroud)
DataFrame(df)如下所示(具有400万个字符串行)
df = pd.DataFrame({'col': ["very definition of the American success story, continually setting the standards of excellence in business, real estate and entertainment.",
"The myriad vulgarities of Donald Trump—examples of which are retailed daily on Web sites and front pages these days—are not news to those of us who have",
"While a fearful nation watched the terrorists attack again, striking the cafés of Paris and the conference rooms of San Bernardino"]})
Run Code Online (Sandbox Code Playgroud)
有什么技巧可以使此字符串搜索更快?例如,首先对数据框进行排序,某种索引方式,将列名更改为数字,从查询中删除“ na = False”等?即使是几毫秒的速度提高也将非常有帮助!
如果子字符串的数量很少,则一次搜索一个子字符串可能会更快,因为您可以将regex=False参数传递给contains,从而加快了速度。
在约6000行的样本数据框中,我有两个子样本测试它,blah.contains("foo", regex=False)| blah.contains("bar", regex=False)快了两倍blah.contains("foo|bar")。您必须使用数据对其进行测试,以查看其扩展方式。