python熊猫过滤涉及列表

问题描述:

我目前在python 2.7中使用熊猫。我的数据框看起来与此类似:python熊猫过滤涉及列表

>>> df 
     0 
1 [1, 2] 
2 [2, 3] 
3 [4, 5] 

是否有可能通过价值列1至过滤行?例如,如果我的过滤器值为2,则过滤器应返回包含前两行的数据帧。

我已经尝试了几种方法。我能想到的最好的事情是做一个列表理解,它返回值存在的行的索引。然后,我可以用索引列表过滤数据帧。但是,如果我想用不同的值过滤多次,这将非常缓慢。理想情况下,我希望使用Pandas函数中的构建来加速此过程。

+0

你可以用'np.in1d'如图所示的答案:[”在熊猫框架列(aka pd.series)'中查找数组元素位置'](http://stackoverflow.com/questions/38083227/finding-an-array-elements-location-in-a-pandas-frame-column -aka-pd-系列)用于搜索多个值。 – Divakar

您可以使用boolean indexing

import pandas as pd 

df = pd.DataFrame({'0':[[1, 2],[2, 3], [4, 5]]}) 
print (df) 
     0 
0 [1, 2] 
1 [2, 3] 
2 [4, 5] 

print (df['0'].apply(lambda x: 2 in x)) 
0  True 
1  True 
2 False 
Name: 0, dtype: bool 

print (df[df['0'].apply(lambda x: 2 in x)]) 
     0 
0 [1, 2] 
1 [2, 3] 
+0

太棒了!谢谢您的帮助。这比我的工作速度快得多。虽然我想象会有一个类似df [2的df [0]]的答案。 – darkyoda182

您也可以使用布尔索引与列表理解:

>>> df[[2 in row for row in df['0']]] 
     0 
0 [1, 2] 
1 [2, 3]