首页 > 解决方案 > Pandas 将字符串比率评估为浮点数

问题描述

我有以下数据框:

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'

我的代码有什么问题,我该如何解决?

标签: pythonpandaseval

解决方案


不要使用pd.evalfor 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

推荐阅读