Skip to content Skip to sidebar Skip to footer

Pandas Query Throws Error When Column Name Starts With A Number

I'm trying to perform a query on the following dataframe: data = {'ab': [1,2,3], 'c1': [1,2,3], 'd': [1,2,3], 'e_f': [1,2,3]} df = pd.DataFrame(data) for cl in df.columns: prin

Solution 1:

query uses pandas.eval, which is documented to "evaluate a Python expression as a string". Your query is not a valid Python expression, because 1d is not valid syntax in Python, so you can't use query to refer to this column that way.

Things in pandas are generally easier if you make sure all your columns are valid Python identifiers.

Solution 2:

You could always get a list of the column names which returns the columns as strings and then query them.

data = {'ab': [1,2,3], 'c1': [1,2,3], 'd': [1,2,3], 'e_f': [1,2,3]}
df = pd.DataFrame(data)
cols = list(df)

So for example cols[0] would be 'ab' and cols[2] would be '1d'.

Post a Comment for "Pandas Query Throws Error When Column Name Starts With A Number"