How do i limit decimal places in python dataframe?

DataFrame.round(decimals=0, *args, **kwargs)[source]#

Round a DataFrame to a variable number of decimal places.

Parameters decimalsint, 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.

ReturnsDataFrame

A DataFrame with the affected columns rounded to the specified number of decimal places.

See also

numpy.around

Round a numpy array to the given number of decimals.

Series.round

Round a Series to the given number of decimals.

Examples

>>> 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

I was trying to rewrite a CSV file using pandas module in python. I tried to multiply the first column (excluding the title) by 60 as below,

 f=001.csv
 Urbs_Data=pd.read_csv(f,header=None)
 Urbs_Data=Urbs_Data.replace("Time_hrs","Time_min")
 Urbs_Data.loc[1:,0]=Urbs_Data.loc[1:,0].astype(float)
 Urbs_Data.loc[1:,0]*=60

It gives me some funny number for the first column, as

124.98000000000002,462.67

130.01999999999998,460.34

135.0,454.36

139.98000000000002,443.29

Is there any way to limit the number of decimal places for those numbers (to 2)? I tried to use the normal round function, it does not work for me.

Here are 4 ways to round values in Pandas DataFrame:

(1) Round to specific decimal places under a single DataFrame column

df['DataFrame column'].round(decimals = number of decimal places needed)

(2) Round up values under a single DataFrame column

df['DataFrame column'].apply(np.ceil)

(3) Round down values under a single DataFrame column

df['DataFrame column'].apply(np.floor)

(4) Round to specific decimals places under an entire DataFrame

df.round(decimals = number of decimal places needed)

Let’s now see how to apply the above approaches using practical examples.

(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 = {'values': [5.52132, 6.572935, 7.21, 8.755, 9.9989]}
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:

df['values'].round(decimals = 3)

So the complete Python code would look like this:

import pandas as pd

data = {'values': [5.52132, 6.572935, 7.21, 8.755, 9.9989]}
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)

Here is the Python code:

import pandas as pd
import numpy as np

data = {'values': [5.52132, 6.572935, 7.21, 8.755, 9.9989]}
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:

df['values'].apply(np.ceil)

Here is the complete Python code to round the values up:

import pandas as pd
import numpy as np

data = {'values': [5.52132, 6.572935, 7.21, 8.755, 9.9989]}
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)

For our example:

df['values'].apply(np.floor)

And here is the full Python code to round the values down:

import pandas as pd
import numpy as np

data = {'values': [5.52132, 6.572935, 7.21, 8.755, 9.9989]}
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 = {'values_1': [5.52132, 6.572935, 7.21, 8.755, 9.9989],
        'values_2': [22.7352, 11.82, 23.75839, 4.22, 15.1173],
        'values_3': ['AAA', 'ABC', 'XYZ', 'AABB', 'PPPP']
        }

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 = {'values_1': [5.52132, 6.572935, 7.21, 8.755, 9.9989],
        'values_2': [22.7352, 11.82, 23.75839, 4.22, 15.1173],
        'values_3': ['AAA', 'ABC', 'XYZ', 'AABB', 'PPPP']
        }

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 = {'values_1': [5.52132, 6.572935, 7.21, 8.755, 9.9989],
        'values_2': [22.7352, 11.82, 23.75839, 4.22, 15.1173],
        'values_3': ['AAA', 'ABC', 'XYZ', 'AABB', 'PPPP']
        }

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 do I reduce decimal places in Python DataFrame?

Lets use the dataframe. round() function to round off all the decimal values in the dataframe to 3 decimal places. Output : Example #2: Use round() function to round off all the columns in dataframe to different places.

How do I limit decimal places in Python?

format() to limit the string representation of a float to two decimal places. Call str. format(*args) with "{:. 2f}" as str and a float as *args to limit the float to two decimal places as a string.

How do I change the number of decimal places in pandas?

4 Ways to Round Values in Pandas DataFrame.
(1) Round to specific decimal places under a single DataFrame column df['DataFrame column'].round(decimals = number of decimal places needed).
(2) Round up values under a single DataFrame column df['DataFrame column'].apply(np.ceil).

How do pandas only show 2 decimal places?

Use pandas. display. float_format to "{:,. 2f}". format to display float values to two decimal places.