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.
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With