6

I have longitude and latitude in two dataframes that are close together. If I run an exact similarity check such as

test_similar = test1_latlon.loc[~test1_latlon['cr'].isin(test2_latlon['cr'])]

I get a lot of failures because a lot of the numbers are off at the 5th decimal place. I want to truncate at after the 3rd decimal. I've seen people format so it shows up truncated, but I want to change the actual value. Using round() rounds off the data and I get even more errors, so is there a way to just drop after 3 decimal points?

geistmate
  • 525
  • 2
  • 5
  • 14
  • related: https://stackoverflow.com/questions/8595973/truncate-to-three-decimals-in-python/57097311 – FObersteiner Aug 03 '20 at 11:52
  • Does this answer your question? [Truncate decimal places of values within a pandas df](https://stackoverflow.com/questions/56782394/truncate-decimal-places-of-values-within-a-pandas-df) – FObersteiner Aug 03 '20 at 11:52

3 Answers3

10

You may want to use numpy.trunc:

import numpy as np
import pandas as pd

df = pd.DataFrame([[1.2366, 1.2310], [1, 1]])
df1 = np.trunc(1000 * df) / 1000
print(df1, type(df1))
#        0      1
# 0  1.236  1.231
# 1  1.000  1.000 <class 'pandas.core.frame.DataFrame'>

Note that df1 is still a DataFrame not a numpy.array

mikey
  • 2,158
  • 1
  • 19
  • 24
  • 1
    Reference, to save an extra search: https://numpy.org/doc/stable/reference/generated/numpy.trunc.html – Nickolay Jan 23 '22 at 14:55
4
import math

value1 = 1.1236
value2 = 1.1266

value1 = math.trunc(1000 * value1) / 1000;
value2 = math.trunc(1000 * value2) / 1000;

#value1 output
1.123

#value2 output
1.126
jonboy
  • 415
  • 4
  • 14
  • 45
  • 2
    in contrast to the accepted answer, this actually accomplishes what the OP asks for ("cut off", i.e. *truncate* to 3 decimal places). – FObersteiner Aug 03 '20 at 11:58
2

As suggested here you can do:

x = 1.123456
float( '%.3f'%(x) )

if you want more decimal places, just change the 3 with any number you need.

Norman
  • 435
  • 6
  • 10
  • 2
    Alright yeah, these are most of the answers I found. I was wondering if there was some pandas way to do it, but this should work for now. Thank you! – geistmate Jun 26 '19 at 21:19
  • First of all: this will round to 3 decimal places, not truncate! Other than that, we have `f-strings` by now in Python, so `float(f"{x:.3f}")` seems more appropriate to me – FObersteiner Aug 03 '20 at 11:54