Pandas 如何查找包含列表的系列元素?

Pandas 如何查找包含列表的系列元素?,pandas,Pandas,我可以找到匹配元组的系列单元格 >>> s = pd.Series([(1,2,3),(4,5,6)], index=[1,2]) >>> print s[s==(1,2,3)] 1 (1, 2, 3) dtype: object 如何对列表执行相同操作: >>> s = pd.Series([[1,2,3],[4,5,6]], index=[1,2]) >>> print s[s==[1,2,3]] ValueEr

我可以找到匹配元组的系列单元格

>>> s = pd.Series([(1,2,3),(4,5,6)], index=[1,2])
>>> print s[s==(1,2,3)]
1    (1, 2, 3)
dtype: object
如何对列表执行相同操作:

>>> s = pd.Series([[1,2,3],[4,5,6]], index=[1,2])
>>> print s[s==[1,2,3]]
ValueError: Arrays were different lengths: 2 vs 3
简易方法

s[s.apply(tuple) == (1, 2, 3)]

1    [1, 2, 3]
dtype: object
不那么容易
假设所有子列表的长度相同


定时
假设一个更大的序列

替代解决方案:

In [352]: s[pd.DataFrame(s.values.tolist(), index=s.index).isin([1,2,3]).all(1)]
Out[352]:
1    [1, 2, 3]
dtype: object
逐步:

In [353]: pd.DataFrame(s.values.tolist(), index=s.index)
Out[353]:
   0  1  2
1  1  2  3
2  4  5  6

In [354]: pd.DataFrame(s.values.tolist(), index=s.index).isin([1,2,3])
Out[354]:
       0      1      2
1   True   True   True
2  False  False  False

In [355]: pd.DataFrame(s.values.tolist(), index=s.index).isin([1,2,3]).all(1)
Out[355]:
1     True
2    False
dtype: bool

这样做的缺点是速度惊人地慢——请看这里的答案:-)我试图找到一种非复杂的替代方法,然后。。。我不能;-)@user48956这么慢我一点也不吃惊。很抱歉我将尝试另一种方法。不过,请注意马苏的评论。
In [352]: s[pd.DataFrame(s.values.tolist(), index=s.index).isin([1,2,3]).all(1)]
Out[352]:
1    [1, 2, 3]
dtype: object
In [353]: pd.DataFrame(s.values.tolist(), index=s.index)
Out[353]:
   0  1  2
1  1  2  3
2  4  5  6

In [354]: pd.DataFrame(s.values.tolist(), index=s.index).isin([1,2,3])
Out[354]:
       0      1      2
1   True   True   True
2  False  False  False

In [355]: pd.DataFrame(s.values.tolist(), index=s.index).isin([1,2,3]).all(1)
Out[355]:
1     True
2    False
dtype: bool