Skip to main content
 首页 » 编程设计

python之如何选择过滤器选择列表中的列列表

2025年05月04日18lvdongjie

我希望能够过滤 DataFrame 并保留列列表位于选择列表中的行。

df = DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3,5], 'C': range(4)}) 

输入:

df 
   A  B  C 
0  5  1  0 
1  6  2  1 
2  3  3  2 
3  4  5  3 
 
filter_list = [(6,2),(3,3)] 

预期结果:

df 
   A  B  C 
1  6  2  1 
2  3  3  2 

我已经尝试过使用 loc 和 map,但我没有设法找到解决方案。

提前致谢。

请您参考如下方法:

In [34]: df = DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3,5], 'C': range(4)}) 
 
In [35]: df 
Out[35]:  
   A  B  C 
0  5  1  0 
1  6  2  1 
2  3  3  2 
3  4  5  3 

创建元组位置的 bool 索引器,然后从框架中选择那些行

In [36]: df.loc[Series(zip(df.A,df.B)).isin([(6,2),(3,3)])] 
Out[36]:  
   A  B  C 
1  6  2  1 
2  3  3  2 

在 0.13(即将发布!)中,您可以这样做,docs here

In [37]: df.isin({ 'A' : [6,3], 'B' : [2,3] }) 
Out[37]:  
       A      B      C 
0  False  False  False 
1   True   True  False 
2   True   True  False 
3  False  False  False 
 
In [38]: indexer = df.isin({ 'A' : [6,3], 'B' : [2,3] }) 
 
In [39]: indexer[['A','B']].all(1) 
Out[39]:  
0    False 
1     True 
2     True 
3    False 
dtype: bool 
 
In [40]: df.loc[indexer[['A','B']].all(1)] 
Out[40]:  
   A  B  C 
1  6  2  1 
2  3  3  2