Python solutions for rounding the values of a pandas DataFrame
Synthetic data
To start, let's generate a DataFrame using synthetic data:
import pandas as pd
import numpy as np
data = np.random.random_sample((5,3))
df = pd.DataFrame(data=data, columns=['A','B','C'])
print(df)
The code displayed above will generate for example:
A B C
0 0.105679 0.874900 0.686569
1 0.418339 0.858791 0.368795
2 0.728953 0.806365 0.405427
3 0.699630 0.911417 0.940126
4 0.906818 0.306024 0.478962
Using the pandas round()
method
Round all columns
When working with Pandas DataFrames, the data can easily be rounded using the round()
method. The round()
method takes as argument the number of decimal.
For example, if we want to round the values down to two decimal place, then the syntax would be:
df.round(2)
With the above code, you'll get:
A B C
0 0.11 0.87 0.69
1 0.42 0.86 0.37
2 0.73 0.81 0.41
3 0.70 0.91 0.94
4 0.91 0.31 0.48
Round values of a given column
df_new = df.copy()
df_new['B'] = df['B'].round(2)
print(df_new)
gives
A B C
0 0.105679 0.87 0.686569
1 0.418339 0.86 0.368795
2 0.728953 0.81 0.405427
3 0.699630 0.91 0.940126
4 0.906818 0.31 0.478962
Round multiple columns
Another example with two columns
df_new = df.copy()
df_new[['A','C']] = df[['A','C']].round(2)
print(df_new)
gives
A B C
0 0.11 0.874900 0.69
1 0.42 0.858791 0.37
2 0.73 0.806365 0.41
3 0.70 0.911417 0.94
4 0.91 0.306024 0.48
Round is not working
If your round operations are not yielding the desired results, try changing the type of DataFrame column first:
df = df.astype('float64')
Using numpy around
Another solution
data = df.to_numpy()
data = np.around(data,2)
df_new = pd.DataFrame(data=data, columns=['A','B','C'])
print(df_new)
With the above code, you'll get:
A B C
0 0.11 0.87 0.69
1 0.42 0.86 0.37
2 0.73 0.81 0.41
3 0.70 0.91 0.94
4 0.91 0.31 0.48
References
Links | Site |
---|---|
pandas.DataFrame.round | pandas.pydata.org |
numpy.around | numpy.org |
Pandas round is not working for DataFrame | stackoverflow |
numpy.random.random | numpy.org |