Home > database >  Roundin numbers with pandas
Roundin numbers with pandas

Time:03-22

I have a pandas dataframe with a column that contains the numbers: [4.534000e-01, 6.580000e-01, 1.349300e 00, 2.069180e 01, 3.498000e-01,...]

I want to round this column up to 3 decimal places, for which I use the round(col) function; however, I have noticed that panda gives me the following: [0.453, 0.658, 1.349, 20.692, 0.35,...] where the last element doesn't have three digits after the decimal.

I would like to have all the numbers rounded with the same amount of digits, for example, like: [0.453, 0.658, 1.349, 20.692, 0.350,...].

How can be done this within pandas?

CodePudding user response:

You can use pandas.DataFrame.round to specify a precision.

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.round.html

import pandas as pd

# instantiate dataframe
dataframe = pd.DataFrame({'column_to_round': [4.534000e-01, 6.580000e-01, 1.349300e 00, 2.069180e 01, 3.498000e-01,]})

# create a new column with this new precision
dataframe['set_decimal_level'] = dataframe.round({'column_to_round': 3})


CodePudding user response:

import pandas as pd    
df = pd.DataFrame([4.534000e-01, 6.580000e-01, 1.349300e 00, 2.069180e 01, 3.498000e-01], columns=['numbers'])
df.round(3)

Prints:

0.453 0.658 1.349 20.692 0.350

  • Related