Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I stack, pivot, or groupby?

I'm still learning how to play with dataframe and still can't make this... I got a dataframe like this:

A  B  C  D1 D2 D3
1  2  3  5  6  7 

I need it to look like:

A  B  C  DA D 
1  2  3  D1 5 
1  2  3  D2 6 
1  2  3  D3 7 

I know I should use something like groupby but I still can't find good documentation.

like image 587
CVM Avatar asked Jan 18 '26 08:01

CVM


2 Answers

This is wide_to_long

ydf=pd.wide_to_long(df,'D',i=['A','B','C'],j='DA').reset_index()
ydf
   A  B  C  DA  D
0  1  2  3   1  5
1  1  2  3   2  6
2  1  2  3   3  7
like image 157
BENY Avatar answered Jan 21 '26 03:01

BENY


Use melt:

df.melt(['A','B','C'], var_name='DA', value_name='D')

Output:

   A  B  C  DA  D
0  1  2  3  D1  5
1  1  2  3  D2  6
2  1  2  3  D3  7

Use set_index and stack

df.set_index(['A','B','C']).stack().reset_index()

Output:

   A  B  C level_3  0
0  1  2  3      D1  5
1  1  2  3      D2  6
2  1  2  3      D3  7

And, you can do housekeeping by renaming column headers etc....

like image 30
Scott Boston Avatar answered Jan 21 '26 05:01

Scott Boston



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!