2017-03-19 16 views
1

我試圖選擇滿足某些條件的熊貓數據框的一個子部分 - 在這種情況下,某個列的每個元素都是一個外部列表。我很驚訝地發現這不起作用,因爲使用.loc的其他條件語句非常簡單。我該如何做這項工作?根據元素是否在外部數組中選擇數據框的一部分

MWE:

import pandas as pd 
import numpy as np 

test_dict = {'first': [0,1,0,0,1,0], 'second': [1,2,3,4,5,6]} 

test_df = pd.DataFrame(test_dict) 

arr1 = [-1,-4,2,-9,8,7,-5,5,-8,0] 
arr2 = [2,5] 


new_df1 = test_df.loc[test_df.second in arr1] 
new_df2 = test_df.loc[test_df.second in arr2] 

print new_df1 
print new_df2 

回答

2

Series.isin()你要找的東西?

In [55]: new_df1 = test_df.loc[test_df.second.isin(arr1)] 

In [56]: new_df2 = test_df.loc[test_df.second.isin(arr2)] 

In [57]: new_df1 
Out[57]: 
    first second 
1  1  2 
4  1  5 

In [58]: new_df2 
Out[58]: 
    first second 
1  1  2 
4  1  5 

,你也可以使用SQL般的風格 - DataFrame.query()

In [60]: test_df.query("second in @arr1") 
Out[60]: 
    first second 
1  1  2 
4  1  5 
+0

這美麗的工作。謝謝! – Arnold