如何在pandas datafram中将十进制128转换为十进制

2024-09-28 22:24:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含许多(但不是全部)十进制128列的数据帧(取自mongodb集合)。我无法对它们进行任何数学或比较(例如,“Decimal128”和“float”实例之间不支持“<;”)。在

什么是最快/最简单的方法来转换所有这些浮动或更简单的内置类型,我可以使用?在

有Decimal128 to_decimal()方法和pandas astype(),但如何在一个step/helper方法中对所有(Decimal128)列执行此操作?在

编辑,我试过:

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

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

但我得到:

^{pr2}$

使用.astype(str).astype(float)转换单个列。在


Tags: to数据实例方法lt类型mongodb数学
2条回答

正在转换完整的数据帧。在

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

对于单列。IDs是列的名称。在

^{pr2}$

测试实施

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

只需使用:

df = df.astype(float)

{{a1}和前面的}方法相比,你也可以使用^或}方法。在

^{pr2}$

我无法在我的系统中重现十进制128。你能看看下一行对你行吗?在

df =  df.apply(lambda x: x.astype(float) if isinstance(x, bson.decimal.Decimal128) else x)

它将检查列是否为Decimal128类型,然后将其转换为float。在

相关问题 更多 >