python - 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'
我的代码有什么问题,我该如何解决?
解决方案
不要使用pd.eval
for 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
推荐阅读
- python - 为什么sql查找重复的速度比我快?
- angular - 选择后保持 Angular Material Auto Complete 打开
- c - 如何在 ECPG 中使用 LISTEN/NOTIFY
- jquery - 如果元素为空或没有任何元素,则将类添加到其父容器,否则删除类
- d - 为什么 D 的变体看起来令人困惑
- python - valueerror 使用序列 sklearn 设置数组元素
- angular - 静态属性的html绑定
- mysql - 我在 MySql 中创建表时遇到问题
- c - 在 Nanopb 的“重复”数据中使用“重复”
- express - 为什么我无法显示以 base64 编码并使用 api 的 angular 7 进行消毒的图像数组