Home > Software engineering >  how to transpose m x n into k x 2 form dataframe in pandas
how to transpose m x n into k x 2 form dataframe in pandas

Time:11-12

I have m x n form dataframe such as belows.

date1         amt1       date2        amt2
2021-01-02     120      1991-01-02     90
2021-01-03     100      1991-01-03     95
2021-01-04     110      1991-01-04     95
....

Is there any way to transpose into k x 2 form dataframe like...

date          amt
2021-01-02     120      
2021-01-03     100      
2021-01-04     110      
...
1991-01-02     90
1991-01-03     95
1991-01-04     95
...

CodePudding user response:

This can be done easily with reshape, although a bit different order:

pd.DataFrame(df.to_numpy().reshape(-1, 2), columns=['date', 'amt'])

Output:

         date  amt
0  2021-01-02  120
1  1991-01-02   90
2  2021-01-03  100
3  1991-01-03   95
4  2021-01-04  110
5  1991-01-04   95

CodePudding user response:

reset_index then u se pd.wide_to long,

df.reset_index(inplace=True)

pd.wide_to_long(df, stubnames=['date', 'amt'], i=['index'], j='id').reset_index(drop=True)



         date  amt
0  2021-01-02  120
1  2021-01-03  100
2  2021-01-04  110
3  1991-01-02   90
4  1991-01-03   95
5  1991-01-04   95
  • Related