Combine pandas DataFrame query() method with isin()

后端 未结 3 1935
礼貌的吻别
礼貌的吻别 2020-12-14 07:53

So I want to use isin() method with df.query(), to select rows with id in a list: id_list. Similar question was asked bef

相关标签:
3条回答
  • 2020-12-14 08:16

    From the docs for query

    You can refer to variables in the environment by prefixing them with an '@' character like @a + b.

    In your case:

    In [38]: df.query('a == @id_list')
    Out[38]:
       a  b  c  d
    0  a  a  3  4
    1  a  a  4  5
    2  b  a  2  3
    3  b  a  1  5
    4  c  b  2  4
    5  c  b  1  2
    
    0 讨论(0)
  • 2020-12-14 08:28

    This appears to work:

    >>> df.query('a == {0}'.format(id_list))
       a  b  c  d
    0  a  a  4  1
    1  a  a  0  7
    2  b  a  2  1
    3  b  a  0  1
    4  c  b  4  0
    5  c  b  4  2
    

    Whether or not it is more clear is a matter of personal taste.

    0 讨论(0)
  • 2020-12-14 08:30

    You can also include the list within the query string:

    >>> df.query('a in ["a", "b", "c"]')
    

    This is the same as:

    >>> df.query('a in @id_list')
    
    0 讨论(0)
提交回复
热议问题