更快地实施pandas应用功能

时间:2017-12-25 17:55:21

标签: python string pandas apply

我有一个pandas dataFrame我想在其中检查一列是否contained

假设:

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) 函数实现

Series

结果是[{1}}

[True, False, True]

这很好,但对于我的dataFrame shape(数百万),需要很长时间。
是否有更好(即更快)的植入?

Unsuccesfull方法

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

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

4 个答案:

答案 0 :(得分:6)

使用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

答案 1 :(得分:5)

尝试zip,在这种情况下明显快于apply

df = pd.concat([df] * 10000)
df.head()
#                A         B
#0  some text here      some
#1    another text  somethin
#2        and this      this
#0  some text here      some
#1    another text  somethin

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

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

# @coldspeed's np.vectorize solution
%timeit v(df.A, df.B)
# 100 loops, best of 3: 4.18 ms per loop

答案 2 :(得分:3)

使用replacenan感染

df.A.replace(dict(zip(df.B.tolist(),[np.nan]*len(df))),regex=True).isnull()
Out[84]: 
0     True
1    False
2     True
Name: A, dtype: bool

修复您的代码

df['A'].str.contains('|'.join(df.B.tolist()))
Out[91]: 
0     True
1    False
2     True
Name: A, dtype: bool

答案 3 :(得分:3)

更新:我们也可以尝试使用numba

from numba import jit

@jit
def check_b_in_a(a,b):
    result = np.zeros(len(a)).astype('bool')
    for i in range(len(a)):
        t = b[i] in a[i]
        if t:
            result[i] = t
    return result

In [100]: check_b_in_a(df.A.values, df.B.values)
Out[100]: array([ True, False,  True], dtype=bool)

又一个矢量化解决方案:

In [50]: df['A'].str.split(expand=True).eq(df['B'], axis=0).any(1)
Out[50]:
0     True
1    False
2     True
dtype: bool

注意:与Psidom和COLDSPEED的解决方案相比,它要慢得多:

In [51]: df = pd.concat([df] * 10000)

# Psidom
In [52]: %timeit [b in a for a, b in zip(df.A, df.B)]
7.45 ms ± 270 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

# cᴏʟᴅsᴘᴇᴇᴅ
In [53]: %timeit v(df.A, df.B)
15.4 ms ± 217 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

# MaxU (1)    
In [54]: %timeit df['A'].str.split(expand=True).eq(df['B'], axis=0).any(1)
185 ms ± 2.29 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

# MaxU (2)    
In [103]: %timeit check_b_in_a(df.A.values, df.B.values)
22.7 ms ± 135 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

# Wen
In [104]: %timeit df.A.replace(dict(zip(df.B.tolist(),[np.nan]*len(df))),regex=True).isnull()
134 ms ± 233 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)