标题听起来比事实更复杂。给定数据
data = [
np.array(['x'], dtype='object'),
np.array(['y'], dtype='object'),
np.array(['z'], dtype='object'),
np.array(['x', 'z', 'y'], dtype='object'),
np.array(['y', 'x'], dtype='object'),
]
s = pd.Series(data)
我想检索
s
的元素,其中 s == np.array(['x'])
。显而易见的方法
c = np.array(['x'])
s[s==c]
不起作用,因为比较中存在 ValueError,抱怨“'长度必须匹配才能比较',(5,), (1,)”。我也试过了
s[s=='x']
仅当
s
的元素本身都只有一个元素时才有效。
有没有办法检索
s
的所有元素,其中 s == c
,无需将元素转换为字符串?
out = s[s.apply(lambda x: x.tolist() == ['x'])]
输出:
0 [x]
dtype: object
检查示例
import pandas as pd
import numpy as np
data1 = [
np.array(['x'], dtype='object'),
np.array(['y'], dtype='object'),
np.array(['z'], dtype='object'),
np.array(['x', 'z', 'y'], dtype='object'),
np.array(['y', 'x'], dtype='object'),
] * 1000000
s1 = pd.Series(data)