当每个值为 ndarray 时,按值获取 pandas 个子系列

Get pandas subseries by values when each value is a ndarray

当 Series 由 ndarray 组成时,我想按值创建一个子系列。

这个有效。

sa = pd.Series([1,2,35,2],index=list('abcd'))
sa[sa==2]

结果

b    2
d    2
dtype: int64

为什么下面的代码不起作用?我应该改变什么?它给出了 ValueError: Lengths must match to compare

sa2 = pd.Series([np.array(['out']), np.array(['2f-right', '2f']), np.array(['out', '2f']), np.array(['out'])], index=list('abcd'))
ar = np.array(['out'])
sa2[sa2 == ar]

这里的比较运算符不理解如何与 np 数组进行相等比较,因此您可以将 applylambda:

一起使用
In [211]:
sa2[sa2.apply(lambda x: (x == ar).all())]

Out[211]:
a    [out]
d    [out]
dtype: object

所以在这里我们与数组进行比较并使用all生成一个布尔掩码