Truncate decimal places of values within a pandas df

Question:

I can truncate individual floats using the truncate function in math. But when trying to pass the same function to a pandas df column I’m getting an error.

import math
import pandas as pd

X = 1.1236

X = math.trunc(1000 * X) / 1000;

#Output
1.123

But when using a pandas df:

d = ({
    'X' : [1.1234,1.1235],           
    })

df = pd.DataFrame(data=d)

df['X'] = math.trunc(1000 * df['X']) / 1000;

Error:

df['X'] = math.trunc(1000 * df['X']) / 1000;

TypeError: type Series doesn't define __trunc__ method
Asked By: jonboy

||

Answers:

You can use applymap

trunc = lambda x: math.trunc(1000 * x) / 1000;

df.applymap(trunc)
Answered By: Anthony Kong

Try changing df['X'] = math.trunc(1000 * df['X']) / 1000; to df['X'] =[math.trunc(1000 * val) / 1000 for val in df['X']]. Hope it helps

Answered By: TavoGLC

I believe the easiest way to achieve this would be using .astype(int)
In your example, it would be:

df[x] = ((df[x]*1000).astype(int).astype(float))/1000

A simple way is converting it into integer values, like this:

df['X'] = df['X'].astype(int)
Answered By: Haddock-san
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.