ShanZhengYang ShanZhengYang - 4 months ago 9
Python Question

Pandas dataframe values refuse to be evaluated as floats with `.apply(eval)`. Why?

Using Python 3.4, I have a Pandas Dataframe

import pandas as pd
df = pd.read_csv('file.csv')
df.head()


giving

animal fraction_decimal
0 cat1 '2/7'
1 cat2 '4/55'
2 cat3 '22/195'
3 cat4 '6/13'
....


I would like to evaluate the values in column
fraction_decimal
to become floats, i.e.

animal fraction_decimal
0 cat1 0.2857142857142857
1 cat2 0.07272727272727272
2 cat3 0.11282051282051282
3 cat4 0.46153846153846156
....


However, using
.apply(eval)
simply doesn't work.

I tried

df['fraction_decimal'].apply(eval)


but this outputs:

0 2/7
1 4/55
2 22/195
3 6/13
....
Name: fraction_decimal, dtype: object


Why doesn't this work? How can this work properly?

Answer
eval("4/2")

2

eval("'4/2'")

'4/2'

eval(eval("'4/2/'"))

2

You have quote characters in your strings. You need to strip them out.

consider:

s = pd.Series(["'1/2'", "'3/4'", "'4/5'", "'6+5'", "'11-7'", "'9*10'"])

Then:

s.str.replace(r'[\'\"]', '').apply(eval)

0     0.50
1     0.75
2     0.80
3    11.00
4     4.00
5    90.00
dtype: float64