python dataframe query with spaces in column name

前端 未结 3 710
庸人自扰
庸人自扰 2021-01-29 02:22

I want to filter dataframe using query

ExcludeData= [1,3,4,5]
dfResult.query(\'Column A in @ExcludeData\')

How do I use Column A in query with

3条回答
  •  甜味超标
    2021-01-29 02:52

    Starting with Pandas v. 0.25, it is possible to refer to columns with names containing spaces if you enclose the column name in backticks within the query.

    Using Pandas 0.25.2:

    >>> df = pd.DataFrame({'a a': [1, 0], 'b b': [1, 1]})
    >>> df
       a a  b b
    0    1    1
    1    0    1
    >>> df.query('`a a`==`b b`')
       a a  b b
    0    1    1
    

    From the API docs: https://pandas.pydata.org/pandas-docs/version/0.25/reference/api/pandas.DataFrame.query.html

    In your case, the usage would be:

    dfResult.query('`Column A` in @ExcludeData')
    

提交回复
热议问题