简体   繁体   English

Pandas每N行重新整理数据帧到列

[英]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'])

在此输入图像描述

and I want to take 3 set of rows and convert them to columns with following order 我想采取3组行,并按照以下顺序将它们转换为列

在此输入图像描述

Numpy reshape doesn't give intended answer Numpy reshape没有给出预期的答案

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

在此输入图像描述

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

Create 3d array by reshape : 通过reshape创建3d数组:

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

This uses the reshape/swapaxes/reshape idiom for rearranging sub-blocks of NumPy arrays. 这使用reshape/swapaxes/reshape惯用法来重新排列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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM