pandas indexing using multiple isin clauses

后端 未结 3 883
陌清茗
陌清茗 2021-01-15 05:40

If I want to do is-in testing on multiple columns at once, I can do:

>>> from pandas import DataFrame
>>> df = DataFrame({\'A\': [1, 2, 3]         


        
3条回答
  •  旧时难觅i
    2021-01-15 06:05

    You could put both conditions in as a mask and use &:

    In [12]:
    
    df[(df['A'].isin([1,3])) & (df['B'].isin([4,7,12]))]
    Out[12]:
       A  B   C
    2  3  7  18
    

    Here the conditions require parentheses () around them due to operator precedence

    Slightly more readable is to use query:

    In [15]:
    
    df.query('A in [1,3] and B in [4,7,12]')
    Out[15]:
       A  B   C
    2  3  7  18
    

提交回复
热议问题