简体   繁体   English

过滤器 pandas df by boolean 系列

[英]Filter pandas df by boolean series

I have a dataframe foo and a True/False series bar :我有一个 dataframe foo和一个真/假系列bar

foo = pd.DataFrame(
    [['a', 1], ['b', 2], ['a', 3]],
    index=[0, 1, 2], columns=['col1', 'col2'])
bar = pd.Series({'a': True, 'b': False})

I want to filter foo on col1 based on the truthiness of bar .我想根据bar的真实性过滤col1上的foo Here are some approaches that work:以下是一些有效的方法:

foo[foo['col1'].isin(bar.where(bar == True).dropna().index)
foo[foo['col1'].isin([k for k, v in bar.to_dict().items() if v])

# desired result
    col1    col2
0   a       1
2   a       3

However, I think both approaches are a bit messy / not so intuitive to read, was wondering if I was missing any basic Pandas filtering concepts that allow for a simpler approach.但是,我认为这两种方法都有点混乱/阅读起来不太直观,想知道我是否遗漏了任何基本的 Pandas 过滤概念,这些概念允许使用更简单的方法。

Use Series.map and index with the result:使用Series.map并索引结果:

foo[foo.col1.map(bar)]

   col1  col2
0    a     1
2    a     3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM