- How to Round Numbers in Pandas DataFrame
- Setup
- Step 1: Round up values to 2 decimal places
- Step 2: Round down numbers in specific column
- Step 3: Round up values
- Step 4: Round down values with decimal precision
- Step 5: Round number to nearest integer
- Step 6: Round values in the whole DataFrame
- Conclusion
- pandas.DataFrame.round#
- 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
- 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 ReplyCancel reply
- Newsletter
- Tags
How to Round Numbers in Pandas DataFrame
We’ll illustrate several examples related to rounding numbers in DataFrame like:
- round number to 2 decimal places
- round up
- round down
- round float to int
- round number to nearest
- round single column
- round whole DataFrame
If you need to format or suppress scientific notation in Pandas please check: How to Suppress and Format Scientific Notation in Pandas
Setup
For this article we are going to create Pandas DataFrame with random float numbers. To generate random float numbers in Python and Pandas we can use the following code:
Generating N random float numbers in Python:
import random nums = [] for i in range(10): x = random.uniform(0.1, 10.0) nums.append(round(x, 5))
Next we will create DataFrame from the above data:
import pandas as pd data = df = pd.DataFrame(data, columns = ['val1', 'val2'])
val1 | val2 | |
---|---|---|
0 | 3.73156 | 3.62060 |
1 | 0.34162 | 0.93644 |
2 | 1.25441 | 9.39390 |
3 | 3.65596 | 2.66972 |
4 | 3.38249 | 6.26096 |
Step 1: Round up values to 2 decimal places
Let’s start by rounding specific column up to 2 decimal places.
The result is a Series from the rounded data:
0 3.73 1 0.34 2 1.25 3 3.66 4 3.38 Name: val1, dtype: float64
So we can see that data was rounded up. For example:
More information about method round is available here: DataFrame.round
Step 2: Round down numbers in specific column
Next let’s cover how to round down a column in Python and Pandas.
We will use np.floor for rounding down:
import numpy as np df['val1'].apply(np.floor)
0 3.0 1 0.0 2 1.0 3 3.0 4 3.0 Name: val1, dtype: float64
If you need decimal precision or custom rounding down please refer to step 4.
Step 3: Round up values
We can use np.ceil to round up numbers in Pandas:
import numpy as np df['val1'].apply(np.ceil)
0 4.0 1 1.0 2 2.0 3 4.0 4 4.0 Name: val1, dtype: float64
If you need decimal precision or custom rounding up please refer to the next step.
Step 4: Round down values with decimal precision
We can define custom function in order to round down values in Pandas with decimal precision.
This allow us to use any custom logic to round numbers in Pandas:
def my_floor(a, precision=0): return np.true_divide(np.floor(a * 10**precision), 10**precision) df['val1'].apply(my_floor, precision=3)
The result is round down float to the 3rd decimal place:
0 3.731 1 0.341 2 1.254 3 3.655 4 3.382 Name: val1, dtype: float64
Step 5: Round number to nearest integer
We can round floats to nearest integer in Pandas by combining:
0 4 1 0 2 1 3 4 4 3 Name: val1, dtype: int64
Step 6: Round values in the whole DataFrame
So far we’ve worked with single columns. If you need to apply rounding operations over the whole DataFrame we can use method round() :
The result is rounding up to 3 decimal places:
val1 | val2 | |
---|---|---|
0 | 3.732 | 3.621 |
1 | 0.342 | 0.936 |
2 | 1.254 | 9.394 |
3 | 3.656 | 2.670 |
4 | 3.382 | 6.261 |
Conclusion
To summarize, in this article, we’ve seen examples of rounding numbers and values in Pandas. We briefly described rounding up and down.
And finally, we’ve seen how to apply rounding on specific columns or the whole DataFrame.
By using DataScientYst — Data Science Simplified, you agree to our Cookie Policy.
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
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
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 ReplyCancel 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.