Home > Mobile >  About shaping 2d dataframe to 3d by index
About shaping 2d dataframe to 3d by index

Time:10-15

I would like to ask is there any function in pandas can reshape dataframe from 2d to 3d by it's index.

    col1  col2  col3
id                  
1      1     2     3
1      4     5     6
1      7     8     9

For example, I have 3 rows with the same id( 1 id row) each one has 3 cols, drop the id and the dataframe is 1x3 (for each row), I want to make it (3x1x3)(by the same id). I tried groupby concat and join, but didn't work. Thanks

CodePudding user response:

You could use the underlying numpy array:

r, c = df.shape
df.values.reshape(r, 1, c)

output:

array([[[1, 2, 3]],

       [[4, 5, 6]],

       [[7, 8, 9]]])

NB. if you want the other dimension: df.values.T.reshape(c, 1, r)

  • Related