6

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
jonboy
  • 415
  • 4
  • 14
  • 45

4 Answers4

8

You can use applymap

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

df.applymap(trunc)
Lucas
  • 6,869
  • 5
  • 29
  • 44
Anthony Kong
  • 37,791
  • 46
  • 172
  • 304
6

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
2

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

TavoGLC
  • 889
  • 11
  • 14
1

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

df['X'] = df['X'].astype(int)
Haddock-san
  • 745
  • 1
  • 12
  • 25