如何使pandas dataframe str.contains搜索速度更快

我在400万行的数据框中搜索子字符串或多个子字符串.

df[df.col.str.contains('Donald',case=True,na=False)]

要么

df[df.col.str.contains('Donald|Trump|Dump',case=True,na=False)]

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"]})

有没有提示让这个字符串搜索更快?
例如,首先排序数据帧,某种索引方式,将列名更改为数字,从查询中删除“na = False”等?即使毫秒的速度增加也会非常有帮助!

解决方法:

如果子串的数量很少,则一次搜索一个可能会更快,因为您可以将regex = False参数传递给contains,从而加快它的速度.

在一个大约6000行的样本DataFrame上,我在两个样本子串上测试它,blah.contains(“foo”,regex = False)| blah.contains(“bar”,regex = False)的速度是blah.contains(“foo | bar”)的两倍.您必须使用您的数据对其进行测试,以了解它的扩展方式.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐