通过np.char.find比较两列pandas数据帧会在非字符串数组上给出TypeError:string操作

tuc*_*son 6 python numpy pandas

我希望比较两个字符串系列,以查找是否包含其他元素.

我首先尝试使用apply,但它很慢:

cols = ['s1','s2']
list_of_series = [pd.Series(['one','sdf'],index=cols), pd.Series(['two','x y two'],index=cols)]
df = pd.DataFrame(list_of_series, columns=cols)
df
    s1  s2
0   one sdf
1   two x y two

df.apply(lambda row: row['s1'] in row['s2'], axis=1)
0    False
1    True 
dtype: bool
Run Code Online (Sandbox Code Playgroud)

它似乎与以下代码一起使用:

x=np.array(['one','two'])
y=np.array(['sdf','x y two'])

np.char.find(y,x)
array([-1,  4])
Run Code Online (Sandbox Code Playgroud)

但如果我有一个数据帧,我会收到一个错误:

np.char.find(df.s2.values,df.s1.values)
TypeError: string operation on non-string array
Run Code Online (Sandbox Code Playgroud)

有人可以建议解决方案吗?

WeN*_*Ben 8

使用findnumpy.core并添加astype str

from numpy.core.defchararray import find
find(df.s2.values.astype(str),df.s1.values.astype(str))!=-1
Out[430]: array([False,  True])
Run Code Online (Sandbox Code Playgroud)