Pandas将数据框每N行转换为列

4
我有一个如下的数据框:
df1=pd.DataFrame(np.arange(24).reshape(6,-1),columns=['a','b','c','d'])

enter image description here

我想把三组行转换成列,顺序如下。

enter image description here

Numpy重塑(reshape)无法得到预期答案。
pd.DataFrame(np.reshape(df1.values,(3,-1)),columns=['a','b','c','d','e','f','g','h'])

enter image description here


你应该考虑接受下面这些精彩答案中的一个。点击此处了解如何接受答案 - Scott Boston
4个回答

8
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

太棒了,谢谢! - Mehtab Pathan
@MehtabPathan,很高兴我能帮上忙 :) - MaxU - stand with Ukraine
分割再堆叠,既美观又高效,谢谢。 - Andrew King

2

通过 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

2

这里使用了 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

2
如果您想要一个纯粹的pandas解决方案:
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接