How to round up a DataFrame in pandas
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 anintvalue 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 libraryimport pandas as pd# creating a dataframedf = pd.DataFrame([(.521, .132), (.019, .675), (.666, .033), (.555, .4489)],columns=['col_1', 'col_2'])print("Before dataframe")print(df) # printing the dataframeprint("After dataframe")# rounding up the values of the dataframe to 2 decimal placesprint(df.round(2))
Explanation
- Line 4: We import the
pandaslibrary. - 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
2decimal places.