Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas
python

How to round up a DataFrame in pandas

Onyejiaku Theophilus Chidalu

Overview

The round() function in pandas is used to round up a DataFrame to a specified number of decimal places.

Syntax

The round() function takes the syntax shown below:

DataFrame.round(decimals=0, *args, **kwargs)
Syntax for the round() function in Pandas

Parameter value

The round() function takes the following optional parameter values:

  • decimals: This takes an int value specifying the number of decimal places to round the values of the DataFrame.
  • *args, **kwargs: These are additional keywords that have no effect on the function but might be accepted for compatibility with the NumPy library.

Return value

The round() function returns a DataFrame holding the rounded values of the columns of the DataFrame.

Example

# A code to illustrate the round() functio in Pandas

# importing the pandas library
import pandas as pd

# creating a dataframe
df = pd.DataFrame([(.521, .132), (.019, .675), (.666, .033), (.555, .4489)],
                  columns=['col_1', 'col_2'])
print("Before dataframe")
print(df) # printing the dataframe
print("After dataframe")
# rounding up the values of the dataframe to 2 decimal places
print(df.round(2))
Implementing the round() function

Explanation

  • Line 4: We import the pandas library.
  • Lines 7–8: We create a DataFrame, df.
  • Line 10: We print the DataFrame, df.
  • Line 13: We round the values of the DataFrame to 2 decimal places.

RELATED TAGS

pandas
python

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring