Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert float to string without losing information - Python

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!

like image 705
Theskywalker15 Avatar asked Apr 26 '26 00:04

Theskywalker15


2 Answers

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.

like image 91
SeaBean Avatar answered Apr 28 '26 13:04

SeaBean


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

  df = df.applymap(lambda x: str(x))
like image 30
AlexMoshi Avatar answered Apr 28 '26 14:04

AlexMoshi