thruxman
thruxman

Reputation: 35

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!

Upvotes: 2

Views: 1961

Answers (4)

Himmat
Himmat

Reputation: 166

df['b'] = pd.eval(df['b'].fillna(1000.0))
df.head()

Upvotes: 0

Rajat Jain
Rajat Jain

Reputation: 2032

Try below:

df = df.fillna(1000.0)

df.b = [eval(str(e)) for e in df.b]

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71610

Or with apply:

df.b = df.b.fillna(1000).apply(pd.eval)

And now:

print(df)

Is:

      a       b
0  John    20.0
1   Bob  1000.0
2   Tim     4.5

Upvotes: 1

BENY
BENY

Reputation: 323326

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

Upvotes: 2

Related Questions