pandas indexing using multiple isin clauses

后端 未结 3 891
陌清茗
陌清茗 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条回答
  •  一个人的身影
    2021-01-15 06:13

    TBH, your current approach looks fine to me; I can't see a way with isin or filter to improve it, because I can't see how to get isin to use only the columns in the dictionary or filter to behave as an all.

    I don't like hardcoding column names, though, so I'd probably write this as

    >>> keep = {'A': [1, 3], 'B': [4, 7, 12]}
    >>> df[df[list(keep)].isin(keep).all(axis=1)]
       A  B   C
    2  3  7  18
    

    or with .loc if I needed a handle.

提交回复
热议问题