Alex
Alex

Reputation: 65

How to retain 2 decimals without rounding in python/pandas?

How can I retrain only 2 decimals for each values in a Pandas series? (I'm working with latitudes and longitudes). dtype is float64.

series = [-74.002568, -74.003085, -74.003546]   

I tried using the round function but as the name suggests, it rounds. I looked into trunc() but this can only remove all decimals. Then I figures why not try running a For loop. I tried the following:

for i in series:
    i = "{0:.2f}".format(i)

I was able to run the code without any errors but it didn't modify the data in any way.

Expected output would be the following:

[-74.00, -74.00, -74.00]    

Anyone knows how to achieve this? Thanks!

Upvotes: 0

Views: 818

Answers (2)

Naveed
Naveed

Reputation: 11650

here is one way to do it

assuming you meant pandas.Series, and if its true then

# you indicated its a series but defined only a list
# assuming you meant pandas.Series, and if its true then

series = [-74.002568, -74.003085, -74.003546]  
s=pd.Series(series)

# use regex extract to pick the number until first two decimal places
out=s.astype(str).str.extract(r"(.*\..{2})")[0]
out

0    -74.00
1    -74.00
2    -74.00
Name: 0, dtype: object

Upvotes: 1

Talha Tayyab
Talha Tayyab

Reputation: 27337

series = [-74.002568, -74.003085, -74.003546]

["%0.2f" % (x,) for x in series]

['-74.00', '-74.00', '-74.00']

It will convert your data to string/object data type. It is just for display purpose. If you want to use it for calculation purpose then you can cast it to float. Then only one digit decimal will be visible.

[float('{0:.2f}'.format(x)) for x in series]
[-74.0, -74.0, -74.0]

Upvotes: 1

Related Questions