4

I have a dataframe like this:

data = [[1, 0, 1],
        [1, 1, 1],
        [0, 0, 1]]

df = pd.DataFrame(data=data, columns=['col1', 'col2', 'col3'])

and from a string like this:

cond_str = ['col1 >= 1', 'col3 >= 1']

and I would like to achieve this:

df.loc[(df['col1'] >= 1) & (df['col3'] >= 1)]

Is there any simple way to do this or do I have to write my own parsing function for this?

2
  • You want ti divide your cond_str list in df.loc[(df['col1'] >= 1) & (df['col3'] >= 1)] with some modification? Commented May 1, 2020 at 14:55
  • Yes I want to use the strings as actual conditions Commented May 1, 2020 at 14:56

2 Answers 2

5

You can use query:

df.query("&".join(cond_str))

which results in

   col1  col2  col3
0     1     0     1
1     1     1     1
Sign up to request clarification or add additional context in comments.

2 Comments

Nice! For some reason I assumed bitwise operators wouldn't work with eval or query, TIL they do :)
@yatu I thought the same the first time I encountered this, but I very much like it. :)
0

you can use eval of python to evaluate a string expression. e.g. for your case

df = pd.DataFrame(data=data, columns=['col1', 'col2', 'col3'])
print(df)

    col1  col2  col3
0     1     0     1
1     1     1     1
2     0     0     1

cond_str_list = ['col1 >= 1', 'col3 >= 1']

cond_str = ' & '.join(['(df.'+i+')' for i in  cond_str_list])

print(cond_str)

df = df[eval(cond_str)]

print(df)

    col1  col2  col3
0     1     0     1
1     1     1     1

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.