Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate decimal places of values within a pandas df

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
like image 852
jonboy Avatar asked Dec 14 '22 11:12

jonboy


2 Answers

You can use applymap

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

df.applymap(trunc)
like image 104
Anthony Kong Avatar answered Jan 15 '23 11:01

Anthony Kong


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
like image 32
Gustavo Linari Rodrigues Avatar answered Jan 15 '23 10:01

Gustavo Linari Rodrigues