我有这样一个数据框:
score year
5/5 2019
1/2 2018
A 2019
我想将字符串形式的得分转换为浮点数,比如5/5=1,1/2=0.5。我使用 to_numeric 方法进行转换,但是由于我的值以 a/b 的形式呈现,它返回了 none。请帮助我解决这个问题。
您可以使用 pandas.eval
和 try-except
语句:
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
如果只有除法是@Goyo更快的解决方案,谢谢:
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
return x
更改为return None
即可。 - jezraeloperator.truediv(*map(int, x.split('/')))
比其他方法快一个数量级,并且不会运行任意代码。 - Stop harming Monica