1

I am new to pandas, I am facing issue with adding df to a string. so I have a conditional string statement like this "'bikes'>20", where bikes are the column name in a data frame. Now I want to add df before 'bikes', How do I do it? I have used this code below but it is not working my code:

x="'bikes'> 20"
x = re.sub(r"([> =!<]==)", r'df[\1]', x)

this gives: 'bikes'> 20 but not adding the df

Want I want is: df['bikes']>20

Is there any way to do it?

1 Answer 1

2

If you replace it like you need, it not working, because "df['bikes']>20" is still string, not column compared by scalar like df['bikes']>20.

Here is possible use DataFrame.query:

df = pd.DataFrame({'bikes':[20,39,44]})

x="'bikes'> 20"

df = df.query(x.replace("'",''))
print (df)
   bikes
1     39
2     44

Working like:

df = df.query("bikes > 20")
print (df)
   bikes
1     39
2     44

EDIT: Solution with pandas.eval:

x="'bikes'> 20"

print (pd.eval("df." + x.replace("'",'')))
0    False
1     True
2     True
dtype: bool

Working like:

print (pd.eval("df.bikes> 20"))

For me not working:

print (pd.eval('df["bikes"]>20'))
    

ValueError: data type must provide an itemsize

6
  • though it is correct. I am looking for something else. So when I add df['bikes']>20. It usually gives the true, false results I am looking for that.
    – krish
    Feb 16, 2021 at 11:58
  • 1
    @krish - I know what mean, but it not working if replace df[] here, because still string.
    – jezrael
    Feb 16, 2021 at 12:00
  • @jezreael-But I thought I could use eval to evaluate that string.
    – krish
    Feb 16, 2021 at 12:01
  • 1
    @krish like (df.eval("df['bikes']>20")) with error UndefinedVariableError: name 'df' is not defined?
    – jezrael
    Feb 16, 2021 at 12:02
  • 1
    @krish - It is possible with . instead [], added to answer.
    – jezrael
    Feb 16, 2021 at 12:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.