1

I have a condition for a pandas dataframe written in a string. Something like this:

"(data['Variable1'] == 1) & (data['Variable2'] == 2)"

Is there a way to apply this condition without using eval() function?

Expected result:

data = data[(data['Variable1'] == 1) & (data['Variable2'] == 2)]
2
  • 1
    Out of curiousity, this looks like a perfect usecase for eval, what's the reason you're not using it? Commented Feb 26, 2020 at 12:20
  • eval works fine on a normal script but i have an error when using eval() within an imported module of my main script. And i honestly don't know why that happens.. Commented Feb 26, 2020 at 12:27

1 Answer 1

6

You can use pandas query to filter required rows

your_query_string = "Variable1 == 1 & Variable2 == 2"
data = data.query(your_query_string)
Sign up to request clarification or add additional context in comments.

Comments

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.