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

时间:2017-05-04 16:21:17

标签: pandas

我可以找到匹配元组的Series单元格......

>>> 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

2 个答案:

答案 0 :(得分:4)

简易方法

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

1    [1, 2, 3]
dtype: object

不太容易
假设所有子列表长度相同

def contains_list(s, l):
    a = np.array(s.values.tolist())
    return (a == l).all(1)

s[contains_list(s, [1, 2, 3])]

1    [1, 2, 3]
dtype: object

<强> 时序
假设一个更大的系列

s = pd.Series([[1,2,3],[4,5,6]] * 1000)

%timeit s[pd.DataFrame(s.values.tolist(), index=s.index).isin([1,2,3]).all(1)]
100 loops, best of 3: 2.22 ms per loop

%timeit s[contains_list(s, [1, 2, 3])]
1000 loops, best of 3: 1.01 ms per loop

%timeit s[s.apply(tuple) == (1, 2, 3)]
1000 loops, best of 3: 1.07 ms per loop

答案 1 :(得分:2)

替代解决方案:

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
相关问题