2

I am trying to use geopy to reverse fetch location deatils based off of location coordinates. Right now I have Lat and Long in two different columns in pandas and both are of float type. Now to use locator.reverse(''), the input must be a string. And when I try to cast float to string, I am losing some information in the form of changed numbers like

df.Lat[0] = 42.279971

df.Lat.astype('str')

df.Lat[0] = 42.27997063

Why is it rounding off? I need exactly the float number as it is given to me?

Thanks for helping!

  • `I need exactly the float number as it is given to me` ... then don't rely on floats, which by their nature are _not_ exact. Use an exact numeric type. What you see is _not_ what you get with floats. – Tim Biegeleisen Jun 22 '21 at 09:11

3 Answers3

2

In your case here, you are not losing precision by converting float to string. Instead, it is because Pandas defaults to show only 6 decimal points for float numbers. When you convert it to string, this output default is not applied.

You can test it by e.g. to set the default float precision to 8:

 pd.set_option("precision", 8)

Then, you will see that before the string conversion, the values is already in that precision already.

SeaBean
  • 22,547
  • 3
  • 13
  • 25
  • I understand now! Thank you for giving an insight of pandas structure! – Theskywalker15 Jun 22 '21 at 09:46
  • @ChayanRaj Why you need to specially convert the string by `repr()` instead of the more common and simpler `astype(str)` ? As the values are already here, no loss of precision, you can use a simple method instead. – SeaBean Jun 22 '21 at 09:54
  • @ChayanRaj Note also that the syntax is `astype(str)` instead of `astype('str')`. No need to enclose `str` in a pair of single quotes. – SeaBean Jun 22 '21 at 09:59
  • This solves the float problem. But if I convert the float to string, there will be more decimal again., like 6.38533 will become 6.385330000000001 – ERIC Apr 22 '22 at 09:45
  • 1
    @ERIC Please be clarified that it is NOT during your conversion from float to string that caused error and leading to MORE decimal points. Your float value ALREADY has the extra decimal points in its internal float type representation (See also what's Tim commented for the question.) Yes, your float number value is actually 6.385330000000001 rather than 6.38533. You probably see 6.385330 (6 decimal points) owing to Pandas default display I mentioned above. I don't have info where your float values come from but you can try to use the Python decimal.Decimal type for better precision. – SeaBean Apr 22 '22 at 17:48
1

I am not sure it can help or not, it convert all cells in dataframe into string

  df = df.applymap(lambda x: str(x))
AlexMoshi
  • 189
  • 1
  • 2
  • 10
0

Use repr() to convert float to string without losing precision:

Try:

df.Lat = df.Lat.apply(lambda x: repr(x))

Or

df.Lat = df.Lat.apply(repr)
Hamza usman ghani
  • 2,264
  • 5
  • 19