Home » Pandas: How to Query Column Name with Space

Pandas: How to Query Column Name with Space

by Erma Khan

You can use the following syntax to perform a pandas query using a column name with a space:

df.query('`this column` == 20')

Note that you must use backticks ( ` ) in the query instead of quotation marks.

The following example shows how to use  this syntax in practice.

Example: Query Column in Pandas DataFrame with Space

Suppose we have the following pandas DataFrame that contains information about various basketball players:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team' : ['A', 'B', 'C', 'D', 'E', 'F', 'G'], 
                    'points scored' : [12, 20, 40, 20, 24, 10, 31]}) 

#view DataFrame
print(df)

  team  points scored
0    A             12
1    B             20
2    C             40
3    D             20
4    E             24
5    F             10
6    G             31

Now suppose that we would like to query for the rows where the points scored column is equal to 20.

If we use the query() function with quotation marks, we’ll receive an error:

#attempt to get rows where points scored column is equal to 20
df.query('"points scored" == 20')

TypeError: argument of type 'int' is not iterable

Instead, we must use the query() function with backticks:

#get rows where points scored column is equal to 20
df.query('`points scored` == 20')

	team	points scored
1	B	20
3	D	20

The query returns the two rows in the DataFrame where the points scored column is equal to 20.

Notice that we don’t receive any error either because we used backticks instead of quotation marks within the query() function.

Additional Resources

The following tutorials explain how to perform other common tasks in pandas:

Pandas: How to Filter Rows Based on String Length
Pandas: How to Drop Rows Based on Condition
Pandas: How to Use “NOT IN” Filter

Related Posts