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
You can use applymap
trunc = lambda x: math.trunc(1000 * x) / 1000;
df.applymap(trunc)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With