- pandas.DataFrame.round#
- Pandas – df.round() – How to round values in pandas
- 1 . Round to certain decimal places –
- 2 . Round up –
- 3 . Round Down –
- Share this:
- Like this:
- Leave a Reply Cancel reply
- Newsletter
- Tags
- 4 Ways to Round Values in Pandas DataFrame
- 4 Ways to Round Values in Pandas DataFrame
- (1) Round to specific decimal places under a single DataFrame column
- (2) Round up values under a single DataFrame column
- (3) Round down values under a single DataFrame column
- (4) Round to specific decimals places under an entire DataFrame
- How to round values in Pandas using round()
- Learn how to use the Pandas round() function and Numpy ceil() and floor() to round numbers to a given number of decimal places, round them up, or round them down.
- Import the packages
- Create a Pandas dataframe
- Round a float with round()
- Round a float to an integer with round()
- Round a float to two decimal places
- Round a number up with ceil()
- Round a number down with floor()
pandas.DataFrame.round#
Round a DataFrame to a variable number of decimal places.
Parameters decimals int, dict, Series
Number of decimal places to round each column to. If an int is given, round each column to the same number of places. Otherwise dict and Series round to variable numbers of places. Column names should be in the keys if decimals is a dict-like, or in the index if decimals is a Series. Any columns not included in decimals will be left as is. Elements of decimals which are not columns of the input will be ignored.
Additional keywords have no effect but might be accepted for compatibility with numpy.
Additional keywords have no effect but might be accepted for compatibility with numpy.
A DataFrame with the affected columns rounded to the specified number of decimal places.
Round a numpy array to the given number of decimals.
Round a Series to the given number of decimals.
>>> df = pd.DataFrame([(.21, .32), (.01, .67), (.66, .03), (.21, .18)], . columns=['dogs', 'cats']) >>> df dogs cats 0 0.21 0.32 1 0.01 0.67 2 0.66 0.03 3 0.21 0.18
By providing an integer each column is rounded to the same number of decimal places
>>> df.round(1) dogs cats 0 0.2 0.3 1 0.0 0.7 2 0.7 0.0 3 0.2 0.2
With a dict, the number of places for specific columns can be specified with the column names as key and the number of decimal places as value
>>> df.round('dogs': 1, 'cats': 0>) dogs cats 0 0.2 0.0 1 0.0 1.0 2 0.7 0.0 3 0.2 0.0
Using a Series, the number of places for specific columns can be specified with the column names as index and the number of decimal places as value
>>> decimals = pd.Series([0, 1], index=['cats', 'dogs']) >>> df.round(decimals) dogs cats 0 0.2 0.0 1 0.0 1.0 2 0.7 0.0 3 0.2 0.0
Pandas – df.round() – How to round values in pandas
In this post, you will learn various ways to round data in pandas.
1 . Round to certain decimal places –
Read a dataset to work with.
import pandas as pd import numpy as np df = pd.read_csv('https://raw.githubusercontent.com/bprasad26/lwd/master/data/gapminder.tsv', sep='\t') df.head()
To round data in pandas, we can use the round method. The round method has a parameter decimal which takes the number of decimal places that you want to round.
Let’s say that you want to round the lifExp column to 2 decimal places.
df['lifeExp'] = df['lifeExp'].round(2)
You can also pass a dictionary to round several columns together. Let’s say you want to round lifeExp to 0 decimal places and gdpPercap to 3 decimal places.
You can also round the whole dataframe at once. Let’s say you want to round all the numeric column to 0 decimal places.
2 . Round up –
To round a numbers up, you can pass np.ceil to the apply method in pandas.
3 . Round Down –
To round down a number, you need to pass np.floor to the apply method in pandas.
Share this:
Like this:
Leave a Reply Cancel reply
Newsletter
Tags
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
4 Ways to Round Values in Pandas DataFrame
Let’s now see how to apply the above approaches using practical examples.
4 Ways to Round Values in Pandas DataFrame
(1) Round to specific decimal places under a single DataFrame column
Suppose that you have a dataset which contains the following values (with varying-length decimal places):
values |
5.52132 |
6.572935 |
7.21 |
8.755 |
9.9989 |
You can then create a DataFrame to capture those values in Python:
import pandas as pd data = df = pd.DataFrame(data, columns = ['values']) print(df)
The DataFrame would look like this in Python:
values 0 5.521320 1 6.572935 2 7.210000 3 8.755000 4 9.998900
Let’s say that your goal is to round the values to 3 decimals places.
Recall that you can round to specific decimals places (under a single DataFrame column) using:
df['DataFrame Column'].round(decimals = number of decimal places needed)
Therefore, in order to round to 3 decimals places, you’ll need to use this syntax:
So the complete Python code would look like this:
import pandas as pd data = df = pd.DataFrame(data, columns = ['values']) df['values'] = df['values'].round(decimals = 3) print(df)
You’ll notice that the values are now rounded to 3 decimals places:
values 0 5.521 1 6.573 2 7.210 3 8.755 4 9.999
Alternatively, you can use NumPy to round the values to 3 decimals places:
np.round(df['DataFrame column'], decimals = number of decimal places needed)
import pandas as pd import numpy as np data = df = pd.DataFrame(data, columns = ['values']) df['values'] = np.round(df['values'], decimals = 3) print(df)
You’ll get the same results using NumPy:
values 0 5.521 1 6.573 2 7.210 3 8.755 4 9.999
(2) Round up values under a single DataFrame column
What if you want to round up the values in your DataFrame?
To accomplish this goal, you can use the second approach to round up values:
df['DataFrame Column'].apply(np.ceil)
In the context of our example, you’ll need to use this syntax:
Here is the complete Python code to round the values up:
import pandas as pd import numpy as np data = df = pd.DataFrame(data, columns = ['values']) df['values'] = df['values'].apply(np.ceil) print(df)
You’ll notice that all the values are now rounded up:
values 0 6.0 1 7.0 2 8.0 3 9.0 4 10.0
(3) Round down values under a single DataFrame column
If you need to round the values down, you can then use the third approach:
df['DataFrame Column'].apply(np.floor)
And here is the full Python code to round the values down:
import pandas as pd import numpy as np data = df = pd.DataFrame(data, columns = ['values']) df['values'] = df['values'].apply(np.floor) print(df)
Run the code, and you’ll get:
values 0 5.0 1 6.0 2 7.0 3 8.0 4 9.0
So far, you’ve seen how to round values under a single DataFrame column.
But what if you’d like to round values across an entire DataFrame that contains multiple columns?
To accomplish this goal, you can use the fourth approach below.
(4) Round to specific decimals places under an entire DataFrame
Suppose that you have a new dataset with multiple columns:
values_1 | values_2 | values_3 |
5.52132 | 22.7352 | AAA |
6.572935 | 11.82 | ABC |
7.21 | 23.75839 | XYZ |
8.755 | 4.22 | AABB |
9.9989 | 15.1173 | PPPP |
This is how the DataFrame would look like in Python:
import pandas as pd data = df = pd.DataFrame(data, columns = ['values_1', 'values_2', 'values_3']) print(df)
Once you run the code in Python, you’ll get the following DataFrame:
values_1 values_2 values_3 0 5.521320 22.73520 AAA 1 6.572935 11.82000 ABC 2 7.210000 23.75839 XYZ 3 8.755000 4.22000 AABB 4 9.998900 15.11730 PPPP
Let’s say that your goal is to round the values to 2 decimals places across all the columns that contain numeric values (i.e., the ‘values_1’ and ‘values_2’ columns).
You can then use the fourth approach to round the values under all the columns that contain numeric values in the DataFrame:
df.round(decimals = number of decimal places needed)
And this is the code that you can use for our example:
import pandas as pd data = df = pd.DataFrame(data, columns = ['values_1', 'values_2', 'values_3']) df = df.round(decimals = 2) print(df)
You’ll see that the values are now rounded to 2 decimal places across the 2 columns that contained the numeric data:
values_1 values_2 values_3 0 5.52 22.74 AAA 1 6.57 11.82 ABC 2 7.21 23.76 XYZ 3 8.76 4.22 AABB 4 10.00 15.12 PPPP
Alternatively, you can get the same results using NumPy:
np.round(df, decimals = number of decimal places needed)
So the complete Python code would look like this:
import pandas as pd import numpy as np data = df = pd.DataFrame(data, columns = ['values_1', 'values_2', 'values_3']) df = np.round(df, decimals = 2) print(df)
You’ll get the same results using NumPy:
values_1 values_2 values_3 0 5.52 22.74 AAA 1 6.57 11.82 ABC 2 7.21 23.76 XYZ 3 8.76 4.22 AABB 4 10.00 15.12 PPPP
How to round values in Pandas using round()
Learn how to use the Pandas round() function and Numpy ceil() and floor() to round numbers to a given number of decimal places, round them up, or round them down.
When working with numeric data in Pandas you’ll often need to round numbers to the nearest whole number, round them up, round them down, or round them to two decimal places. While Pandas includes the round() function for basic rounding, you’ll need to use a little simple Numpy to do anything slightly more complex. In this quick and easy tutorial, I’ll show you how it’s done.
Import the packages
To get started, open a Jupyter notebook and import the Pandas library and the Numpy library using the as pd and as np naming conventions. We’ll need Numpy as well as Pandas for rounding, since you can’t do everything with standard Pandas functionality.
import pandas as pd import numpy as np
Create a Pandas dataframe
Next, create a dataframe using the from_dict() function. We’ll include some dummy float values with lots of decimal places so we can round them in various ways.
data = 'sku': ['1', '2', '3', '4'], 'price': [28.345343, 34.99, 29.000000, 42.3937289]> df = pd.DataFrame.from_dict(data) df
Round a float with round()
If you have a float value you want to round to the nearest whole number you can append the round() method with no arguments. We’ll call df[‘price].round() and assign the rounded value to a new column called price_round . As you’ll see, this rounds the number but doesn’t change the dtype of the data, so the value will still be a float .
df['price_round'] = df['price'].round() df
Round a float to an integer with round()
Chances are, if you’re rounding a float value to the nearest whole number, you’ll most likely want an integer value like 28, rather than a float like 28.0. To solve this you can change the dtype of the float to int using the astype() method.
df['price_round'] = df['price'].round().astype(int) df
Round a float to two decimal places
By passing in a value to the round() method you can define the number of decimal places or trailing digits returned. For example, df[‘price’].round(2) will round 28.345343 to 28.35.
df['price_round_2'] = df['price'].round(2) df
sku | price | price_round | price_round_2 | |
---|---|---|---|---|
0 | 1 | 28.345343 | 28 | 28.35 |
1 | 2 | 34.990000 | 35 | 34.99 |
2 | 3 | 29.000000 | 29 | 29.00 |
3 | 4 | 42.393729 | 42 | 42.39 |
Round a number up with ceil()
To round a number up in Pandas you need to use Numpy’s ceil() method via the Pandas apply() function. This will calculate the ceiling — or next highest number — of a given float value, so 28.345343 will become 29 rather than the 28 you’d get if you just used round() .
df['price_round_up'] = df['price'].apply(np.ceil) df
sku | price | price_round | price_round_2 | price_round_up | |
---|---|---|---|---|---|
0 | 1 | 28.345343 | 28.0 | 28.35 | 29.0 |
1 | 2 | 34.990000 | 35.0 | 34.99 | 35.0 |
2 | 3 | 29.000000 | 29.0 | 29.00 | 29.0 |
3 | 4 | 42.393729 | 42.0 | 42.39 | 43.0 |
Round a number down with floor()
Similarly, to round a number down in Pandas you need to use the Numpy floor() method along with the Pandas apply() function. Given a value like 34.990000 this will round the number down to 34, rather than the 35 you’d get with round() .
df['price_round_down'] = df['price'].apply(np.floor) df
sku | price | price_round | price_round_2 | price_round_up | price_round_down | |
---|---|---|---|---|---|---|
0 | 1 | 28.345343 | 28.0 | 28.35 | 29.0 | 28.0 |
1 | 2 | 34.990000 | 35.0 | 34.99 | 35.0 | 34.0 |
2 | 3 | 29.000000 | 29.0 | 29.00 | 29.0 | 29.0 |
3 | 4 | 42.393729 | 42.0 | 42.39 | 43.0 | 42.0 |
Matt Clarke, Thursday, January 05, 2023