gpt4 book ai didi

python - pd.Series.str.contains 的矢量化版本

转载 作者:行者123 更新时间:2023-12-03 21:59:20 25 4
gpt4 key购买 nike

给定两个索引相同的 pd.Series 字符串,检查第一个 pd.Series 的每个元素是否是第二个 pd.Series 的相应元素的子字符串的最有效方法是什么?

例子:

s1 = pd.Series(['cat', 'dog', 'ham'])
s2 = pd.Series(['catbird', 'frog', 'hamster'])

pd.Series([t[0] in t[1] for t in zip(s1, s2)], index=s1.index)

产量
0     True
1 False
2 True
dtype: bool

最佳答案

我认为你的解决方案很好,因为还有 Pandas .str函数使用循环(并处理缺失值),所以有时会更慢。

我通过小的修改更改了解决方案 - 将元组解包为变量 tv ,在测试数据中它更快一点:

np.random.seed(2020)

N = 10000
s1 = pd.Series(np.random.choice(list(string.ascii_letters), size=N))
s2 = pd.DataFrame(np.random.choice(list(string.ascii_letters), size=(N, 3))).sum(axis=1)

In [82]: %timeit (pd.Series([t[0] in t[1] for t in zip(s1, s2)], index=s1.index))
3.47 ms ± 271 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [83]: %timeit (pd.Series([t in v for t, v in zip(s1, s2)], index=s1.index))
2.89 ms ± 130 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

关于python - pd.Series.str.contains 的矢量化版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60631298/

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