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.
*args
Additional keywords have no effect but might be accepted for compatibility with numpy.
**kwargs
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.
By providing an integer each column is rounded to the same number of decimal places
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
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
Pandas как округлить значения в столбце
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.round() function is used to round a DataFrame to a variable number of decimal places. This function provides the flexibility to round different columns by different places.
Syntax:DataFrame.round(decimals=0, *args, **kwargs)
Parameters :
decimals : 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.Returns : DataFrame object
Example #1: Use round() function to round off all columns in the dataframe to 3 decimal places
Note : We need to populate our dataframe with decimal values. Let’s use numpy random function to achieve the task.
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:
Next we will create DataFrame from the above data:
DataFrame looks like:
| 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:
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:
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:
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:
The result is round down float to the 3rd decimal place:
Step 5: Round number to nearest integer
We can round floats to nearest integer in Pandas by combining:
- round()
- astype()
and the result is:
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
Округлите DataFrame до переменного числа десятичных разрядов.
Parameters десятичные дроби : int, dict, Series
Количество десятичных знаков,до которых нужно округлить каждый столбец.Если задано значение int,округлите каждый столбец до одного и того же числа знаков.В противном случае dict и Series округляются до переменного числа знаков.Имена столбцов должны быть в ключах,если decimals является диктующим,или в индексе,если decimals является Серией.Любые столбцы,не включенные в decimals будут оставлены без изменений.Элементы decimals которые не являются столбцами входа,будут проигнорированы.
*args
Дополнительные ключевые слова не имеют эффекта,но могут быть приняты для совместимости с numpy.
**kwargs
Дополнительные ключевые слова не имеют эффекта,но могут быть приняты для совместимости с numpy.
Фрейм DataFrame с соответствующими столбцами,округленными до заданного числа десятичных разрядов.
Округлите числовой массив до заданного числа десятичных разрядов.
Округлите серию до заданного числа десятичных знаков.
Предоставляя целое число,каждый столбец округляется до одинакового количества знаков после запятой.
С помощью диктата можно задать количество мест для конкретных столбцов,при этом имена столбцов могут быть определены как ключевые,а количество десятичных разрядов-как значение
Используя Серию,можно указать количество мест для конкретных столбцов,при этом названия столбцов могут быть указаны как индекс,а количество знаков после запятой-как значение.