gpt4 book ai didi

python - 检查数据框中列的字符串值是否以元组的字符串元素开头(除了 str.startswith)

转载 作者:太空宇宙 更新时间:2023-11-03 20:18:27 25 4
gpt4 key购买 nike

我有一个带有随机值的 pandas 数据框列("457645","458762496","1113423453"...),我需要检查这些值是否以元组的元素开头(“323”,“229”,“111”)

在本例中,“1113423453” 应该如此。

我尝试过df[column].str.startswith(tuple),效果很好;但对于大量数据(2M df 行和 3K 元组元素),与 10K df 行和 3K 元组元素(1.47 秒)相比,它变得慢得多(大约 28 秒)。

有没有更有效的方法?

最佳答案

I have tried df[column].str.startswith(tuple), which works fine … but i'm searching for a more efficient way to do it if it's possible

由于 startswith() 并未针对大量前缀字符串进行优化,并且仅对它们进行线性搜索,因此此处使用二分搜索可能更有效。为此,我们需要对前缀进行排序。

from bisect import bisect_right
s = sorted(tuple)
df[column].apply(lambda str: str.startswith(s[bisect_right(s, str)-1]))

is it possible to extract the prefix into a new column of the dataframe?

是的,e。 G。使用此功能:

def startwiths(str):
prefix = s[bisect_right(s, str)-1]
if str.startswith(prefix): return prefix

df['new column'] = df[column].apply(startwiths)

关于python - 检查数据框中列的字符串值是否以元组的字符串元素开头(除了 str.startswith),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58305553/

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