Pandas 将字符串比率评估为浮点数

Pandas evaluate a string ratio into a float

我有以下数据框:

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 行,它会 return 丑陋的错误,因此需要分别转换每个值:

df['Ratios'] = 1/df['Ratios'].str.replace(':','/').apply(pd.eval)

但是你的错误似乎还有一些非数值和 :

超过 100 行的错误:

AttributeError: 'PandasExprVisitor' object has no attribute '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

如果您的数据格式正确,则使用 Series.str.split 的替代解决方案,

s = df['Ratios'].str.split(':')
df['Ratios'] = s.str[1].astype(float) / s.str[0].astype(float)

# print(df)
         Date    Ratios
0  2009-08-23  0.500000
1  2018-08-22  0.500000
2  2019-10-24  0.500000
3  2020-10-28  0.666667

我编写了一个函数,可以帮助您从比率中生成小数部分。

def convertFraction(x):
    arr = x.split(":")
    fraction = float(arr[0])/float(arr[1])
    return fraction

df["Fractions"] = df["Ratios"].apply(lambda x:convertFraction(x))

print(df)