简体   繁体   中英

Filter pandas df by boolean series

I have a dataframe foo and a True/False series 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 . 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.

Use Series.map and index with the result:

foo[foo.col1.map(bar)]

   col1  col2
0    a     1
2    a     3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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