gpt4 book ai didi

python - 如何使 pandas dataframe str.contains 搜索更快

转载 作者:太空狗 更新时间:2023-10-30 00:54:26 69 4
gpt4 key购买 nike

我正在 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") 的两倍。您必须使用您的数据对其进行测试,以了解其扩展性。

关于python - 如何使 pandas dataframe str.contains 搜索更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37894003/

69 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com