Liza
Liza

Reputation: 971

How to stack pandas data frame rows into two halves?

I am dealing with a data frame with 6 columns, Below is the example df

     a   b   c   d   e   f
     1   2   3   4   5   6
     7   8   9   10  11  12

Following is the new data frame which I expect:

     col1   col2   col3
     1      2      3
     4      5      6
     7      8      9
     10     11     12

Please note the order of the row elements, The first row from the original df, becomes the first two rows of the new df, the second row from the original df becomes the next two.

Please advice me to achieve the required new df. Thanks in advance.

Upvotes: 1

Views: 123

Answers (1)

akuiper
akuiper

Reputation: 214927

You can reshape the values (which is numpy array) to 3 columns, and construct a new data frame out of it:

pd.DataFrame(df.values.reshape(-1, 3), columns=["Col"+str(i) for i in range(1,4)])

#Col1   Col2   Col3
#0  1      2      3
#1  4      5      6
#2  7      8      9
#3  10    11     12

Upvotes: 1

Related Questions