Search code examples
pythonpandaspivot-table

Pandas Pivot_Table index values shown but columns and counts do not show


I am trying to do a simple pivot table and for some reason the columns and counts do not appear in the results.

Sample df (as Dict):

{'Date': {0: '2024-02-20',  1: '2024-02-18',  2: '2024-02-16',  3: '2024-02-01',  4: '2024-02-20',  5: '2024-01-21',  6: '2024-02-20',  7: '2024-01-21',  8: '2024-02-20',  9: '2024-02-20',  10: '2024-02-20'},
 'Status': {0: 'Won',  1: 'Credit Pulled',  2: 'Credit Pulled',  3: 'Credit Pulled',  4: 'Pre Credit Pull',  5: 'Credit Pulled',  6: 'Credit Pulled',  7: 'Won',  8: 'Awaiting Bank Account',  9: 'Credit Pulled',  10: 'Credit Pulled'}}
dfPivot = pd.pivot_table(data=df,index=['Date'],columns=['Status'],aggfunc="count")

Results: Only the date column is displayed in dfPivot.

Expectation (made in Excel): Excel Pivot Sample

I tried changing the "columns" to "values" and that displays the counts correctly. I tried specifying the column names with a list, but that does not work.

Any suggestions?


Solution

  • Try this (I hope I understood what you are after):

    df['cnt'] = 1
    dfPivot = pd.pivot_table(data=df,index=['Date'],columns=['Status'], values=['cnt'], aggfunc="count")
    dfPivot.fillna(0, inplace=True)
    dfPivot
    
                                 cnt                                   
    Status     Awaiting Bank Account Credit Pulled Pre Credit Pull  Won
    Date                                                               
    2024-01-21                   0.0           1.0             0.0  1.0
    2024-02-01                   0.0           1.0             0.0  0.0
    2024-02-16                   0.0           1.0             0.0  0.0
    2024-02-18                   0.0           1.0             0.0  0.0
    2024-02-20                   1.0           3.0             1.0  1.0