Pandas Group transpose single colum and row in Python

Question:

I’m trying to group a pandas dataframe and transpose one single column and one single row(?). See example image below. I have tried using the function GroupBy and Pivot. Any ideas? 🙂

Example grouped table

import pandas as pd

name = 'Name'
account = 'Account'
price = 'Price'
date = 'Date'
month = 'Month'

dictionary = {
  name: 
      ['aaa','aaa','bbb','bbb','bbb','ccc','ccc','ccc'],
  account: 
      [22, 33, 22, 22, 33, 12, 12, 10],
  price: 
      [100, 345, 345, 667, 1_033, 234, 10, 12],
  date: 
      ['01-05-2022', '02-06-2022', '04-04-2022', '23-01-2022', '01-05-2022', '02-02-2022', '04-02-2022', '23-01-2022']
}

df = pd.DataFrame(data=dictionary)

df[date] = pd.to_datetime(df[date], format='%d-%m-%Y')
df[month] = pd.DatetimeIndex(df[date]).month

group = df.groupby([month, name]).agg({price:['count', 'sum']})

group.transpose()
Asked By: Kristoffer

||

Answers:

This may work for you:

dfo = (pd.pivot_table(df, index='Name', columns='Month', values='Price', aggfunc=['sum','count'])
           .stack(level=0).fillna(0).astype(int))
print(dfo)

Result

Month         1    2    4     5    6
Name                                
aaa  count    0    0    0     1    1
     sum      0    0    0   100  345
bbb  count    1    0    1     1    0
     sum    667    0  345  1033    0
ccc  count    1    2    0     0    0
     sum     12  244    0     0    0

Headers On Same Line

dfo = (pd.pivot_table(df, index='Name', columns='Month', values='Price', aggfunc=['sum','count'])
           .stack(level=0).fillna(0).astype(int)
           .rename_axis(('Name','Month'), axis=0)
           .rename_axis(None, axis=1).reset_index())
print(dfo)

Same Line Header Result

  Name  Month    1    2    4     5    6
0  aaa  count    0    0    0     1    1
1  aaa    sum    0    0    0   100  345
2  bbb  count    1    0    1     1    0
3  bbb    sum  667    0  345  1033    0
4  ccc  count    1    2    0     0    0
5  ccc    sum   12  244    0     0    0
Answered By: jch