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
Answers:
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
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
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