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

问题描述 投票:0回答:2

我有以下数据框:

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'

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

python pandas eval
2个回答
0
投票

不要将pd.eval用作Series,因为如果更多地像是100行,则会返回uggly错误,因此需要:

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

0
投票

尝试:

df['Ratios'] = 1/pd.eval(df['Ratios'].str.replace(':','/'))
print(df)
© www.soinside.com 2019 - 2024. All rights reserved.