Search code examples
pandasgroup-bypivot

How to do pivot of Column which has values like 1, 0 and -1 and count the total number


So i have column like date, Paid (it contains 1 (Yes), 0(Now) and -1(Ongoing)) now i wanted ouptut as below

date          1  0  -1   Total Paid0%  Paid1%
1st March    10  5   5   20     50%    50%
2nd March    5   4   1   10    40%      50%
...

Please see the screenshot pd.pivot_table(df, columns = 'PAID', values = 'PAID', index = 'DATE', aggfunc = 'count')


Solution

  • First use crosstab:

    df1 = pd.crosstab(df['date'], df['Paid'])
    

    Then sum values per rows by DataFrame.sum:

    tot = df1.sum(axis=1)
    

    Divide columns 0,1 by sum in variable tot, change formating for percentages by DataFrame.applymap and change columns names in rename:

     df2 = (df1[[0,1]].div(tot, axis=0)
                      .applymap(lambda x: f"{x:.2%}")
                      .rename(columns=lambda x: f'Paid{x}%'))
    

    Create column Total by DataFrame.assign and append by DataFrame.join new DataFrame df2:

    final = df1.assign(Total = tot).join(df2)
    print (final)
    Paid       -1  0  1  Total  Paid0%  Paid1%
    date                                      
    1st March   1  2  2      5  40.00%  40.00%
    2nd March   0  1  3      4  25.00%  75.00%