0

I'm working on a DataFrame query using 2 variables. The first variable is the column label and the second is a list of values. What I want to do is select all row where that column has a value contained in that list. The strange thing is that if I write the column label as a string there is no error, while referencing the variable containing the column label gives the following error:

Traceback (most recent call last):
  File "C:\Python\Python36\lib\site-packages\pandas\indexes\base.py", line 2134, in get_loc
    return self._engine.get_loc(key)
  File "pandas\index.pyx", line 132, in pandas.index.IndexEngine.get_loc (pandas\index.c:4433)
  File "pandas\index.pyx", line 151, in pandas.index.IndexEngine.get_loc (pandas\index.c:4238)
  File "pandas\index.pyx", line 388, in pandas.index.Int64Engine._check_type (pandas\index.c:8171)
KeyError: False

This is the working code:

rhs_values_list = df1["RHS"].tolist()
query = "shoe_size in @rhs_values_list"
result_set = df2.query(query)

while this rises the above error:

rhs_values_list = df1["RHS"].tolist()
col = "shoe_size"
query = "@col in @rhs_values_list"
result_set = df2.query(query)

Is there something wrong with second version of the query?

1 Answer 1

3

What you are doing is executing the actual query with @col in the string, not the value you bound to that variable. You can use string interpolation e.g:

  rhs_values_list = df1["RHS"].tolist()
    col = "shoe_size"
    query = "{} in @rhs_values_list".format(col)
    result_set = df2.query(relaxed_query)
Sign up to request clarification or add additional context in comments.

3 Comments

FYI using string interpolation like this is generally not a great idea. Ideally you want to use a library that allows parameterized queries and will sanitize any variables.
In this case, SQL injection is not a concern because you cannot pass table mutation queries to df.query.
Good to know Pandas got your back :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.