如何在 pandas 数据框中将Decimal128转换为十进制 [英] How to convert Decimal128 to decimal in pandas dataframe

查看:216
本文介绍了如何在 pandas 数据框中将Decimal128转换为十进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据帧,其中包含许多(但不是全部)Decimal128列(取自mongodb集合).我无法对其进行任何数学运算或比较(例如,在'Decimal128'和'float'实例之间不支持'<').

I have a dataframe with many (But not all) Decimal128 columns (taken from a mongodb collection). I can't perform any math or comparisons on them (e.g. '<' not supported between instances of 'Decimal128' and 'float').

将所有这些转换为float或我可以使用的一些更简单的内置类型的最快/最简单的方法是什么?

What is the quickest/easiest way to convert all these to float or some simpler built-in type that i can work with?

有Decimal128 to_decimal()方法和pandas astype(),但是如何在一个步骤/帮助器方法中对所有(十进制128)列执行此操作?

There is the Decimal128 to_decimal() method, and pandas astype(), but how can I do it for all (the decimal128) columns in one step/helper method?

编辑,我已经尝试过:

testdf =  my_df.apply(lambda x: x.astype(str).astype(float) if isinstance(x, Decimal128) else x)

testdf[testdf["MyCol"] > 80].head()

但是我得到了

TypeError: '>' not supported between instances of 'Decimal128' and 'int'

使用.astype(str).astype(float)转换单个列即可.

Converting a single column using .astype(str).astype(float) works.

推荐答案

投射完整的DataFrame.

Casting full DataFrame.

df = df.astype(str).astype(float)

对于单列. ID 是列的名称.

For single column. IDs is the name of the column.

df["IDs"] = df.IDs.astype(str).astype(float)

测试实施

from pprint import pprint
import bson
df = pd.DataFrame()
y = []
for i in range(1,6):
    i = i *2/3.5
    y.append(bson.decimal128.Decimal128(str(i)))
pprint(y)
df["D128"] = y
df["D128"] = df.D128.astype(str).astype(float)
print("\n", df)

输出:

[Decimal128('0.5714285714285714'),
 Decimal128('1.1428571428571428'),
 Decimal128('1.7142857142857142'),
 Decimal128('2.2857142857142856'),
 Decimal128('2.857142857142857')]

        D128
0  0.571429
1  1.142857
2  1.714286
3  2.285714
4  2.857143

这篇关于如何在 pandas 数据框中将Decimal128转换为十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆