Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 658
Mehtab Pathan Avatar asked Dec 10 '22 07:12

Mehtab Pathan


1 Answers

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
like image 166
MaxU - stop WAR against UA Avatar answered Dec 21 '22 01:12

MaxU - stop WAR against UA