Python 根据元素是否在外部数组中选择数据帧的一部分

Python 根据元素是否在外部数组中选择数据帧的一部分,python,pandas,dataframe,selection,Python,Pandas,Dataframe,Selection,我试图选择满足特定条件的pandas数据帧的一个子部分——在本例中,特定列的每个元素都是外部列表的一部分。我惊讶地发现这不起作用,因为使用.loc的其他条件语句非常简单。我怎样才能做到这一点 MWE: 你在找什么 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]:

我试图选择满足特定条件的pandas数据帧的一个子部分——在本例中,特定列的每个元素都是外部列表的一部分。我惊讶地发现这不起作用,因为使用.loc的其他条件语句非常简单。我怎样才能做到这一点

MWE:

你在找什么

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的样式-:

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
In [60]: test_df.query("second in @arr1")
Out[60]:
   first  second
1      1       2
4      1       5