我有以下数据框:
Date Ratios
2009-08-23 2:1
2018-08-22 2:1
2019-10-24 2:1
2020-10-28 3:2
我想将比率转换为浮点数,所以2:1变成2/1变成0.5,3:2变成0.66667。
我用下面的公式
df['Ratios'] = 1/pd.eval(df['Ratios'].str.replace(':','/'))
但我不断收到这个错误 TypeError: unsupported operand type(s) for /: 'int' and 'list'
我的代码有什么问题,我该如何解决?
不要pd.eval
用于Series
,因为如果更多的是100行,它将返回难看的错误,因此需要分别转换每个值:
df['Ratios'] = 1/df['Ratios'].str.replace(':','/').apply(pd.eval)
但是,您的错误似乎也包含一些非数字值:
。
超过100行的错误:
AttributeError:“ PandasExprVisitor”对象没有属性“ visit_Ellipsis”
如果仍然无法正常工作,您可以尝试测试自定义函数中的数据是否正确:
print (df)
Date Ratios
0 2009-08-23 2:1r
1 2018-08-22 2:1
2 2019-10-24 2:1
3 2020-10-28 3:2
def f(x):
try:
pd.eval(x)
return False
except:
return True
df = df[df['Ratios'].str.replace(':','/').apply(f)]
print (df)
Date Ratios
0 2009-08-23 2:1r
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句