Search code examples
pythonpandasdataframefractions

Converting Fractions in a Dataframe Series to Float


In Python 3.x, how can I convert a Dataframe column containing fraction strings and NaN values into floats? I've tried a few things but haven't found an adequate solution.

So if I have a dataframe, "df", that looks like:

     a      b
0   John   20/1
1   Bob    NaN
2   Tim    9/2

How can I end up with df looking like:

      a      b
0   John   20.0
1   Bob    1000.0
2   Tim    4.5

Thank you for any guidance you're willing to provide!


Solution

  • Magic of eval from pandas

    df.b=pd.eval(df.b.fillna(1000))
    df
    Out[25]: 
          a     b
    0  John    20
    1   Bob  1000
    2   Tim   4.5