Python 熊猫将数据帧每N行重新整形为列

Python 熊猫将数据帧每N行重新整形为列,python,pandas,numpy,reshape,Python,Pandas,Numpy,Reshape,我有一个数据框,如下所示: df1=pd.DataFrame(np.arange(24).reshape(6,-1),columns=['a','b','c','d']) 我想取3组行,按以下顺序将它们转换为列 Numpy重塑没有给出预期的答案 通过重塑创建三维阵列: a = np.hstack(np.reshape(df1.values,(-1, 3, len(df1.columns)))) df = pd.DataFrame(a,columns=['a','b','c','d','e'

我有一个数据框,如下所示:

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

我想取3组行,按以下顺序将它们转换为列

Numpy重塑没有给出预期的答案
通过
重塑
创建三维阵列:

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
这将使用用于重新排列NumPy阵列的子块

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

如果您想要纯熊猫解决方案:

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

   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

太棒了,谢谢@MehtabPathan,很高兴我能帮助你:)你应该考虑下面的一个很棒的答案。
df.set_index([df.index % 3, df.index // 3])\
  .unstack()\
  .sort_index(level=1, axis=1)\
  .set_axis(list('abcdefgh'), axis=1, inplace=False)
   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