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

标签 python pandas

我希望能够过滤 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

关于python - 如何选择过滤器选择列表中的列列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19980587/

相关文章:

python - 用一组新值替换看起来像列中的元素范围并将其余值设置为 0

python - Pandas 数据框从长到宽转换,每个索引的行数不同

python - seaborn和networkx可以通过matplotlib集成到GUI中吗?

python - 在 DataFrame 中组合多个列

python - 使用另一个数据帧中的行号从现有数据帧创建新的 pandas 数据帧

Python根据双索引中的星期几创建虚拟变量

python - Foreach 循环使用 BeautifulSoup/Mechanize/Python 获取下一页链接

python - Pandas tz_localize : Infer dst when localizing timezone in data with duplicates

python - 正确确定比例因子

python - 紧固查询elasticsearch