1
>>> df['X'].head()
0    25+4
1    25+5
2    15+3
3    20+2
4    20+3
Name: X, dtype: object

How do I evaluate this so my dataframe is this:

>>> df['X'].head()
0    29
1    30
2    18
3    22
4    23

Name: X, dtype: int64
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
bopeng
  • 13
  • 2
  • 1
    A word of warning: `eval`ing arbitrary Python code is [potentially dangerous](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html), especially if the code comes from an external source that you cannot 100% trust. Remember [Little Bobby Tables](https://xkcd.com/327/). – ali_m May 07 '16 at 02:59

1 Answers1

1

Although there are security concerns, you can use eval to evaluate each element using a lambda expression.

df = pd.DataFrame({'X': ['25+4', '25+5', '15+3', '20+2', '20+3']})

>>> df
      X
0  25+4
1  25+5
2  15+3
3  20+2
4  20+3

>>> df.X.apply(lambda x: eval(x))
0    29
1    30
2    18
3    22
4    23
Name: X, dtype: int64

For a description of security concerns, see:

Alexander
  • 105,104
  • 32
  • 201
  • 196