17

I wish to only round values in the DataFrame for display purposes, when I use head() or tail() but I want the DataFrame to retain the original values.

I tried using the round method but it changes the values in the original DataFrame. I don't wish to create a separate copy each time for this purpose.

Is there any other way than creating a separate copy?

I'm having trouble glancing at values because some columns have e^10 notations. I'd just like to have a look at two to three decimal places maximum and not keep glancing at exponent values.

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
xennom
  • 171
  • 1
  • 5

2 Answers2

34

You can temporarily change the display option:

with pd.option_context('display.precision', 3):
    print(df.head())
    
       0      1      2      3      4
0 -0.462 -0.698 -2.030  0.766 -1.670
1  0.925  0.603 -1.062  1.026 -0.096
2  0.589  0.819 -1.040 -0.162  2.467
3 -1.169  0.637 -0.435  0.584  1.232
4 -0.704 -0.623  1.226  0.507  0.507

Or change it permanently:

pd.set_option('display.precision', 3)

A simple print(df.head().round(3)) would also work in this case. They will not change the DataFrame in place.

ayhan
  • 70,170
  • 20
  • 182
  • 203
1

If you want to change the precision for a specific DataFrame, you can use panda's Styler.format. To make every column in the DataFrame have the same precision you can use:

df = pd.DataFrame(np.random.random(size=(15, 4)), columns=list('ABCD'))
df.head().style.format(precision=2)

       A       B       C       D
0   0.24    1.00    0.69    0.63
1   0.99    0.22    0.09    0.34
2   0.33    0.24    0.86    0.04
3   0.65    0.13    0.54    0.18
4   0.50    0.70    0.44    0.19

To make a specific column have a different precision you can format it using a dictionary:

df.head().style.format({'D':'{:0.5f}'},precision=2)

       A       B       C          D
0   0.24    1.00    0.69    0.63088
1   0.99    0.22    0.09    0.34297
2   0.33    0.24    0.86    0.03709
3   0.65    0.13    0.54    0.18494
4   0.50    0.70    0.44    0.18531
Kyle
  • 307
  • 2
  • 9