如果没有丢失数据,您可以使用numpy.reshape http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html:
print (np.reshape(df.values,(2,5)))
[['Andrew' 'School of Music' 'Music: Sound of the wind' 'Dr. Seuss'
'Dr.Sass']
['Michelle' 'School of Theatrics' 'Music: Voice' 'Dr. A' 'Dr. B']]
print (pd.DataFrame(np.reshape(df.values,(2,5)),
columns=['Name','School','Music','Mentor1','Mentor2']))
Name School Music Mentor1 Mentor2
0 Andrew School of Music Music: Sound of the wind Dr. Seuss Dr.Sass
1 Michelle School of Theatrics Music: Voice Dr. A Dr. B
生成更通用的解决方案length
of new array
by shape http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shape.html除以列数:
print (pd.DataFrame(np.reshape(df.values,(df.shape[0] / 5,5)),
columns=['Name','School','Music','Mentor1','Mentor2']))
Name School Music Mentor1 Mentor2
0 Andrew School of Music Music: Sound of the wind Dr. Seuss Dr.Sass
1 Michelle School of Theatrics Music: Voice Dr. A Dr. B
谢谢皮尔方 https://stackoverflow.com/questions/39761366/transpose-the-data-in-a-column-every-nth-rows-in-pandas/39762293?noredirect=1#comment66820514_39762293另一个解决方案:
print (pd.DataFrame(df.values.reshape(-1, 5),
columns=['Name','School','Music','Mentor1','Mentor2']))