+2 votes
in Programming Languages by (28.5k points)
I have a DataFrame with float values. Those values have different decimal places. How can I round all elements to the 'k' (e.g., 2 or 3) number of decimal places?

1 Answer

+1 vote
by (48.9k points)

You can use the round() function of Pandas DataFrame to round all elements. You need to pass the number of decimal places as an argument.

Here is an example:

>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({'A':np.random.random(5), 'B':np.random.random(5)})
>>> df
          A         B
0  0.592639  0.387378
1  0.308161  0.259731
2  0.896155  0.963413
3  0.010093  0.776740
4  0.633199  0.402313
>>> df.round(decimals=2)
      A     B
0  0.59  0.39
1  0.31  0.26
2  0.90  0.96
3  0.01  0.78
4  0.63  0.40
>>> df.round(decimals=3)
       A      B
0  0.593  0.387
1  0.308  0.260
2  0.896  0.963
3  0.010  0.777
4  0.633  0.402


...