Pandas DataFrame | round method
Start your free 7-days trial now!
Pandas DataFrame.round(~)
method returns a DataFrame with all its numerical values rounded according to the specified parameters.
Parameters
1. decimals
| int
or dict
or Series
| optional
The number of decimals to round to. The columns that are rounded depends on the data type of decimals
:
Type | Description |
---|---|
| All values in the DataFrame will be rounded. |
| Only the specified columns will be rounded. |
| Only the specified columns will be rounded. |
Note that decimals=1
would mean that values like 1.52
will be rounded to 1.5
. In contrast, decimals=-1
would round values like 13
to 10
(nearest 10th).
As for data types dict
and Series
, the key and indexes will be the names of the columns you want to round, with the corresponding values being the number of decimals to round to. See examples below for clarification.
By default, decimals=0
, which means that the values are rounded to the nearest integer.
Numbers ending in 5
will be rounded down. For instance, numbers such as 2.5
and 3.45
will be rounded down to 2
and 3.4
, respectively, instead of rounding up.
Return Value
A DataFrame
with its values rounded according to the supplied parameter.
Examples
Rounding all values to nearest integer
Consider the following DataFrame:
df
A B0 1.05 3.451 2.42 4.90
To round to the nearest integer, just call round()
directly:
df.round()
A B0 1.0 3.01 2.0 5.0
Rounding all values to the nearest 10th
Consider the following DataFrame:
df
A B0 4 121 6 18
To round to the nearest 10th, supply -1
as the argument:
df.round(-1)
A B0 0 101 10 20
Rounding all values to the 1st decimal place
Consider the following DataFrame:
df
A B0 1.07 3.451 2.42 4.90
To round to the 1st decimal place, supply 1
as the argument:
df.round(1)
A B0 1.1 3.41 2.4 4.9
Notice how 3.45
was rounded down to 3.4
instead of rounding up to 3.5
.
Rounding certain columns only
Instead of providing an int
, we can provide either a dict
or a Series
to round certain columns.
Passing in Dict
When providing a dict
, the key must be the column name, while the value must be the decimal place to round to.
As an example, consider the following DataFrame:
df
A B0 4.2 12.41 6.6 18.9
To round only column A
to the nearest integer, and leave column B
intact:
df.round({"A":0})
A B0 4.0 12.41 7.0 18.9
Notice how column B
was left as is.
Passing in Series
Similarly, when providing a Series
, the indexes must be the column name, while the value must be the decimal place to round to.
Consider the following DataFrame:
df
A B0 4.2 12.41 6.6 18.9
To round only column A
to the nearest integer, and leave column B
intact:
df.round(decimals)
A B0 4.0 12.41 7.0 18.9
Notice how column B
was left as is.