0

I want to change the table display format so I used pivot_table but final result is completely changed I don't know why.

Here is my code.

import pandas as pd
df = pd.DataFrame(
    [
        ('2015/1/1', 73.23234, 'salgrp'), 
        ('2015/2/1', 53.23234, 'salgrp'), 
        ('2015/3/1', 0.00, 'salgrp'), 
        ('2015/2/1', 30.3, 'salnic'), 
        ('2015/3/1', 10, 'salnic'), 
        ('2015/4/1', 31.2, 'saldsc'), 
        ('2015/5/1', 33.23234, 'saldsc'), 
    ], 
    columns=['date', 'amount', 'formula'])
df = df.round(2)
print(df)
df = df.pivot_table(columns=['date'], index=['formula'], values=['amount'])
print(df)

And here is the output.

       date  amount formula
0  2015/1/1   73.23  salgrp
1  2015/2/1   53.23  salgrp
2  2015/3/1    0.00  salgrp
3  2015/2/1   30.30  salnic
4  2015/3/1   10.00  salnic
5  2015/4/1   31.20  saldsc
6  2015/5/1   33.23  saldsc
          amount                                    
date    2015/1/1 2015/2/1 2015/3/1 2015/4/1 2015/5/1
formula                                             
saldsc       NaN      NaN      NaN     31.2    33.23
salgrp     73.23    53.23      0.0      NaN      NaN
salnic       NaN    30.30     10.0      NaN      NaN

My question is why pivot table result changed and how to maintain two decimal places across all the result. ? Final result should comes like this 0.00 and 31.20 and 10.00

Cloud Learner
  • 111
  • 1
  • 1
  • 8

1 Answers1

1

Internally, they are still float and have the same values. If you do want to see them in two decimal places and you are using Jupyter Notebook, you can use style.format (without print)

(df.pivot_table(index='formula', columns='date', values='amount')
         .style.format("{:.2f}")
)
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74