Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Dataframe reshaping with stack and unstack

I am trying to messing with pandas stack and unstack. I was wondering if it is possible to reshape my data in this way.

This is my sample data which I am practicing.

ID,Value1,Value2
1,3,12
1,4,13
1,5,14
1,6,15
1,7,16
2,8,17
2,9,18
2,10,19
2,11,20

And I want to reshape in this way.

ID 
1   Index(Extra Column) Value1, value2
    1                      3    12
    2                      4    13
    3                      5    14
    4                      6    15
    5                      7    16

2
    1                      8    17
    2                      9    18
    3                      10   19
    4                      11   20

I tried this

df1 = pd.DataFrame(df[['Value1', 'Value2']], index= df['ID']).stack()

or

df1 = df.set_index(['ID']).stack()

this changes Value1 and Value2 from column to rows which I dont want.

Any Ideas ?

like image 679
user96564 Avatar asked Nov 25 '25 13:11

user96564


2 Answers

I propose set_index + cumcount here:

df.set_index(['ID', df.groupby('ID').cumcount() + 1])

      Value1  Value2
ID                  
1  1       3      12
   2       4      13
   3       5      14
   4       6      15
   5       7      16
2  1       8      17
   2       9      18
   3      10      19
   4      11      20

Another option is using concat:

pd.concat({k : g.reset_index(drop=True) for k, g in df.drop('ID', 1).groupby(df.ID)})

     Value1  Value2
1 0       3      12
  1       4      13
  2       5      14
  3       6      15
  4       7      16
2 0       8      17
  1       9      18
  2      10      19
  3      11      20
like image 144
cs95 Avatar answered Nov 28 '25 01:11

cs95


One way from apply

df.groupby('ID')[['Value1','Value2']].apply(lambda x : x.reset_index(drop=True))
Out[662]: 
      Value1  Value2
ID                  
1  0       3      12
   1       4      13
   2       5      14
   3       6      15
   4       7      16
2  0       8      17
   1       9      18
   2      10      19
   3      11      20
like image 45
BENY Avatar answered Nov 28 '25 01:11

BENY



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!