将特定列从浮点数转换为小数 [英] Convert specific columns from float to Decimal
问题描述
我有一个数据框,我需要将特定的列范围从浮点数转换为小数(并让它们全部保留小数点后 5 位).我很难转换列.有人可以帮助我这样做吗,最好使用 iloc
?我在下面有一个示例代码,它说明了我在寻找什么(有生成示例数据的代码).运行此程序时收到以下错误.
I have a dataframe where I need to convert specific column ranges from floats to decimals (and have them all go out 5 decimal places).
I am having a difficult time converting the columns.
Can someone help me do so, preferably using iloc
?
I have a sample code below that illustrates what I am looking for (there is code to generate sample data). I receive the following error when I run this.
追溯:
"TypeError: ('不支持从系列到十进制的转换','发生在索引 B')"
"TypeError: ('conversion from Series to Decimal is not supported', 'occurred at index B')"
import pandas as pd
from pandas import util
import numpy as np
from decimal import Decimal
df= util.testing.makeDataFrame()
df.head()
df.iloc[:, 1:4].apply(Decimal)
推荐答案
apply
在 Dataframe 上应用一个函数到该数据框的所有 Series
列.您必须更进一步,将 Decimal
应用于每个 Series
的各个单元格:
apply
on a Dataframe applies a function to all the columns of that dataframe which are Series
. You have to go one step further and apply Decimal
to the individual cells of each Series
:
df.iloc[:, 1:4] = df.iloc[:, 1:4].apply(lambda x: x.apply(Decimal))
如果你想量化
十进制,只需使用另一个lambda
:
If you want to quantize
the Decimal, just use another lambda
:
df.iloc[:, 1:4] = df.iloc[:, 1:4].apply(lambda x: x.apply(
lambda y: Decimal(y).quantize(Decimal('1.00000'))))
这篇关于将特定列从浮点数转换为小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!