'How to convert our dataframe without using pivot in python?
i have a dataframe
df = pd.Dataframe ({"nam":["a", "b", "a", "b"],
"dat":["2022-01-01","2022-01-01","2022-01-01","2022-01-01"],
"tim": ['10:00:00', '10:00:00' , '11:00:00', '11:00:00'],
"va1":[1,2,3,4],
"val2":[11,22,33,44]}
)
and i want to convert it into without using pd.pivot_table as i cant see the results of pivot in debug mode in pycharm ( ref to pandas pivot_table : NoneType object is not callable ) and hence i cant progress with my code ahead in debug mode.
Hence looking for an alternate option of pd.pivot_table which can provide me this result.
| nam | dat | val1 | val1 | val2 | val2 |
--------------------------------------------------------------------------------
tim | | | '10:00:00' | '11:00:00' | '10:00:00' | '11:00:00' |
--------------------------------------------------------------------------------
0 | "a" | "2022-01-01"| 1 | 3 | 11 | 33 |
--------------------------------------------------------------------------------
1 | "b" | "2022-01-01"| 2 | 4 | 22 | 44 |
--------------------------------------------------------------------------------
Solution 1:[1]
Here are alternatives - if no aggregation necessary:
df1 = df.pivot(index=['nam','dat'], columns='tim')
print (df1)
va1 val2
tim 10:00:00 11:00:00 10:00:00 11:00:00
nam dat
a 2022-01-01 1 3 11 33
b 2022-01-01 2 4 22 44
df1 = df.set_index(['nam','dat','tim']).unstack()
print (df1)
va1 val2
tim 10:00:00 11:00:00 10:00:00 11:00:00
nam dat
a 2022-01-01 1 3 11 33
b 2022-01-01 2 4 22 44
If need aggregate like pivot_table:
df2 = df.groupby(['nam','dat','tim']).mean().unstack()
print (df2)
va1 val2
tim 10:00:00 11:00:00 10:00:00 11:00:00
nam dat
a 2022-01-01 1 3 11 33
b 2022-01-01 2 4 22 44
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jezrael |
