0

I have an issue with strings. Is it possible to get data frame and column name out of string? Like below,

my input:
    string = "df['homes']+df['age']"

I want this out of the string-like below

excepted output:

string = df['homes']+df['age']
krish
  • 61
  • 9

2 Answers2

3

Use pandas.eval:

>>> import pandas as pd
>>> string = "df['homes']+df['age']"
>>> string = pd.eval(string)
Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52
  • Sorry I didn't mention this, I was aware of eval. But the problem with eval is when we give division or too many arithmetic symbols it gives a wrong answer any other method to do it? – krish Feb 15 '21 at 10:19
1

This can be done with the infamous exec() method:

my_input = input()

exec(my_input)

But it is very dangerous, do not use the code snippet above.

See Why should exec() and eval() be avoided?

Red
  • 26,798
  • 7
  • 36
  • 58