我有这样的数据框:
score year
5/5 2019
1/2 2018
A 2019
我想将分数从字符串转换为 float ,例如 5/5=1、1/2=0.5,我尝试使用 to_numeric,但由于我的值是 a/b 形式,所以它没有返回任何值。请帮我解决这个问题。
最佳答案
您可以使用 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
关于python - 将 a/b 字符串转换为在 pandas 中 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55059365/