熊猫从两列之间的操作开始



>我有一个包含两列的熊猫数据帧,我需要在其中检查 A 列每行的值在哪里是一个字符串,该字符串以 B 列的相应行的值开头,反之亦然。

似乎 Series 方法.str.startswith无法处理矢量化输入,因此我需要在列表推导式中压缩两列,并使用与两列中的任何一列具有相同索引的新pd.Series

我希望这是一个矢量化操作,.str访问器可用于对可迭代对象进行操作,但像这样的东西返回 NaN:

df = pd.DataFrame(data={'a':['x','yy'], 'b':['xyz','uvw']})
df['a'].str.startswith(df['b'])

而我的工作解决方案如下:

pd.Series(index=df.index, data=[a.startswith(b) or b.startswith(a) for a,b in zip(df['a'],df['b'])])

我怀疑可能有更好的方法来解决这个问题,因为它也将有利于系列上的所有字符串方法。

有没有更漂亮或更有效的方法可以做到这一点?

一个想法是使用np.vecorize,但是因为处理字符串的性能与您的解决方案一样好一点:

def fun (a,b):
return a.startswith(b) or b.startswith(a)
f = np.vectorize(fun)
a = pd.Series(f(df['a'],df['b']), index=df.index)
print (a)
0     True
1    False
dtype: bool
<小时 />
df = pd.DataFrame(data={'a':['x','yy'], 'b':['xyz','uvw']})
df = pd.concat([df] * 10000, ignore_index=True)
In [132]: %timeit pd.Series(index=df.index, data=[a.startswith(b) or b.startswith(a) for a,b in df[['a', 'b']].to_numpy()])
42.3 ms ± 516 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [133]: %timeit pd.Series(f(df['a'],df['b']), index=df.index)
9.81 ms ± 119 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [134]: %timeit pd.Series(index=df.index, data=[a.startswith(b) or b.startswith(a) for a,b in zip(df['a'],df['b'])])
14.1 ms ± 262 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
<小时 />
#sammywemmy solution
In [135]: %timeit pd.Series([any((a.startswith(b), b.startswith(a))) for a, b in df.to_numpy()], index=df.index)
46.3 ms ± 683 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

最新更新