gpt4 book ai didi

python - 更快地实现 pandas apply 功能

转载 作者:太空宇宙 更新时间:2023-11-03 12:15:48 26 4
gpt4 key购买 nike

我有一个 pandas dataFrame,我想在其中检查一列是否包含在另一列中。

假设:

df = DataFrame({'A': ['some text here', 'another text', 'and this'], 
'B': ['some', 'somethin', 'this']})

我想检查 df.B[0] 是否在 df.A[0], df.B[1]df.A[1] 等中

当前方法

我有以下apply函数实现

df.apply(lambda x: x[1] in x[0], axis=1)

结果是 [True, False, True]Series

很好,但是对于我的 dataFrame shape(数以百万计),它需要相当长的时间。
有更好(即更快)的植入吗?

不成功的方法

我尝试了 pandas.Series.str.contains 方法,但它只能采用字符串作为模式。

df['A'].str.contains(df['B'], regex=False)

最佳答案

使用 np.vectorize - 绕过 apply 开销,因此应该会更快一些。

v = np.vectorize(lambda x, y: y in x)

v(df.A, df.B)
array([ True, False, True], dtype=bool)

这是时间比较 -

df = pd.concat([df] * 10000)

%timeit df.apply(lambda x: x[1] in x[0], axis=1)
1 loop, best of 3: 1.32 s per loop

%timeit v(df.A, df.B)
100 loops, best of 3: 5.55 ms per loop

# Psidom's answer
%timeit [b in a for a, b in zip(df.A, df.B)]
100 loops, best of 3: 3.34 ms per loop

两者都是非常有竞争力的选择!

编辑,为 Wen 和 Max 的回答添加时间 -

# Wen's answer
%timeit df.A.replace(dict(zip(df.B.tolist(),[np.nan]*len(df))),regex=True).isnull()
10 loops, best of 3: 49.1 ms per loop

# MaxU's answer
%timeit df['A'].str.split(expand=True).eq(df['B'], axis=0).any(1)
10 loops, best of 3: 87.8 ms per loop

关于python - 更快地实现 pandas apply 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47970891/

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