Table of Contents
To query a column name with a space in Pandas, the user can enclose the column name in square brackets [] or use the .loc method with the column name in quotes. This allows Pandas to recognize the column name as a single entity and retrieve the desired data from the column.
Pandas: Query Column Name with Space
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.
The following tutorials explain how to perform other common tasks in pandas:
Cite this article
stats writer (2024). How can I query a column name with a space in Pandas?. PSYCHOLOGICAL SCALES. Retrieved from https://scales.arabpsychology.com/stats/how-can-i-query-a-column-name-with-a-space-in-pandas/
stats writer. "How can I query a column name with a space in Pandas?." PSYCHOLOGICAL SCALES, 26 Jun. 2024, https://scales.arabpsychology.com/stats/how-can-i-query-a-column-name-with-a-space-in-pandas/.
stats writer. "How can I query a column name with a space in Pandas?." PSYCHOLOGICAL SCALES, 2024. https://scales.arabpsychology.com/stats/how-can-i-query-a-column-name-with-a-space-in-pandas/.
stats writer (2024) 'How can I query a column name with a space in Pandas?', PSYCHOLOGICAL SCALES. Available at: https://scales.arabpsychology.com/stats/how-can-i-query-a-column-name-with-a-space-in-pandas/.
[1] stats writer, "How can I query a column name with a space in Pandas?," PSYCHOLOGICAL SCALES, vol. X, no. Y, ص Z-Z, June, 2024.
stats writer. How can I query a column name with a space in Pandas?. PSYCHOLOGICAL SCALES. 2024;vol(issue):pages.
