Transformation of Pandas Dataframe from long to wide format

Question:

I want to transform below dataframe in wide format

Date category cat-count
1-1-2022 Login 5
1-1-2022 Accounts 10
2-1-2022 Login 9
3-1-2022 Accounts 10
3-1-2022 Login 15

Desired Output

Date Login Accounts
1-1-2022 5 10
2-1-2022 9 0
3-1-2022 10 15

How can i get this Output by Pandas python or any python method

Asked By: Shaelander Chauhan

||

Answers:

Use pandas.pivot_table

import pandas as pd

df = pd.DataFrame({'date': ['1-1-2022', '1-1-2022', '2-1-2022', '3-1-2022', '3-1-2022'],
                   'cat': ['Login', 'Accounts', 'Login', 'Accounts', 'Login'],
                   'cat-cnt': [5, 10, 9, 10, 15]})

df_new = pd.pivot_table(df, index=['date'], columns=['cat'], fill_value=0.0)

Result:

df_new =

          cat-cnt      
cat      Accounts Login
date                   
1-1-2022       10     5
2-1-2022        0     9
3-1-2022       10    15


df_new['cat-cnt']['Accounts'] =

date
1-1-2022    10
2-1-2022     0
3-1-2022    10
Name: Accounts, dtype: int64
Answered By: J. Choi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.