如果没有数据丢失,你可以使用numpy.reshape
:
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
通过将 shape
除以列数生成新 array
的更一般的解决方案:
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
感谢piRSquared提供的另一种解决方案:
print (pd.DataFrame(df.values.reshape(-1, 5),
columns=['Name','School','Music','Mentor1','Mentor2']))
pd.DataFrame(df.values.reshape(-1, 5), columns=['Name','School','Music','Mentor1','Mentor2']))
- piRSquared