python - 更快地实现 pandas apply 功能

标签 python string pandas apply

我有一个 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/

相关文章:

python-3.x - 在 Pandas 中旋转时遇到麻烦(在R中传播)

python - 在 Pandas 中同时在所有列中使用 apply 函数

python - 在具有 500e6 行的 hdf5 pytable 中查找重复项

python - Plotly:如何在不更改数据源的情况下更改 go.pie 图表的图例?

python - 找到一条直线上的最大等距点

java - 从字符串中选择大写字母并将其转换为字符数组

r - 在单词的字母之间插入空格

python - 验证 RTSP 流 URL [python] 的最佳方法是什么

java - 用空格对字符串值进行排序

python - Pandas 对具有固定行数的数据帧进行重新采样