Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a/b string to float in pandas

I have dataframe like this:

        score  year
         5/5   2019
         1/2   2018
          A    2019

I want to convert score from string to float like 5/5=1, 1/2=0.5, I tried to_numeric but as my values are in a/b form it's returning me none. Please help me with this.

like image 463
Chris_007 Avatar asked Mar 08 '19 08:03

Chris_007


1 Answers

You can use pandas.eval with try-except statement:

def func(x):
    try:
        return pd.eval(x)
    except Exception:
        #for return original
        return x
        #for return None
        #return None

df['new'] = df['score'].apply(func)
print (df)
  score  year  new
0   5/5  2019    1
1   1/2  2018  0.5
2     A  2019    A

If there is only division is faster solution from @Goyo, thank you:

import operator

def func(x):
    try:
        return operator.truediv(*map(int, x.split('/')))
    except Exception:
        #for return original
        return x
        #for return None
        #return None
like image 53
jezrael Avatar answered Oct 30 '22 14:10

jezrael