Mehtab Pathan
Mehtab Pathan

Reputation: 483

Pandas reshape dataframe every N rows to columns

I have a dataframe as follows :

df1=pd.DataFrame(np.arange(24).reshape(6,-1),columns=['a','b','c','d'])

enter image description here

and I want to take 3 set of rows and convert them to columns with following order

enter image description here

Numpy reshape doesn't give intended answer

pd.DataFrame(np.reshape(df1.values,(3,-1)),columns=['a','b','c','d','e','f','g','h'])

enter image description here

Upvotes: 4

Views: 6300

Answers (4)

Scott Boston
Scott Boston

Reputation: 153460

If you want a pure pandas solution:

df.set_index([df.index % 3, df.index // 3])\
  .unstack()\
  .sort_index(level=1, axis=1)\
  .set_axis(list('abcdefgh'), axis=1, inplace=False)

Output:

   a  b   c   d   e   f   g   h
0  0  1   2   3  12  13  14  15
1  4  5   6   7  16  17  18  19
2  8  9  10  11  20  21  22  23

Upvotes: 2

unutbu
unutbu

Reputation: 879591

This uses the reshape/swapaxes/reshape idiom for rearranging sub-blocks of NumPy arrays.

In [26]: pd.DataFrame(df1.values.reshape(2,3,4).swapaxes(0,1).reshape(3,-1), columns=['a','b','c','d','e','f','g','h'])
Out[26]: 
   a  b   c   d   e   f   g   h
0  0  1   2   3  12  13  14  15
1  4  5   6   7  16  17  18  19
2  8  9  10  11  20  21  22  23

Upvotes: 2

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210842

In [258]: df = pd.DataFrame(np.hstack(np.split(df1, 2)))

In [259]: df
Out[259]:
   0  1   2   3   4   5   6   7
0  0  1   2   3  12  13  14  15
1  4  5   6   7  16  17  18  19
2  8  9  10  11  20  21  22  23

In [260]: import string

In [261]: df.columns = list(string.ascii_lowercase[:len(df.columns)])

In [262]: df
Out[262]:
   a  b   c   d   e   f   g   h
0  0  1   2   3  12  13  14  15
1  4  5   6   7  16  17  18  19
2  8  9  10  11  20  21  22  23

Upvotes: 8

jezrael
jezrael

Reputation: 862681

Create 3d array by reshape:

a = np.hstack(np.reshape(df1.values,(-1, 3, len(df1.columns))))
df = pd.DataFrame(a,columns=['a','b','c','d','e','f','g','h'])
print (df)
   a  b   c   d   e   f   g   h
0  0  1   2   3  12  13  14  15
1  4  5   6   7  16  17  18  19
2  8  9  10  11  20  21  22  23

Upvotes: 2

Related Questions