2016-07-07 78 views
0

我目前在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

回答

2

您可以使用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

1

您也可以使用布爾索引與列表理解:

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