Dhimmel90
Dhimmel90

Reputation: 39

Convert specific columns from float to Decimal

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.

Traceback:

"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)

Upvotes: 2

Views: 12063

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 148880

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))

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'))))

Upvotes: 2

David Erickson
David Erickson

Reputation: 16683

@Serge Ballesta If you use round instead of decimal, then that would round it appropriately; however, as you may know that then converts it to a float. If your goal is to keep the column as a "Decimal", which in Pandas is an "Object" rather than a float, then, you could add .astype(str) to the end after rounding to the desired amount of digits.

import pandas as pd 
from pandas import util
import numpy as np
from decimal import Decimal

df = util.testing.makeDataFrame()    
df.iloc[:, 1:4] = df.iloc[:, 1:4].round(5).astype(str)
df

Upvotes: 0

Related Questions