Transpose the data in a column every nth rows in PANDAS

If no data are missing, you can use 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

More general solution with generating length of new array by shape divide by number of columns:

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

Thank you piRSquared for another solution:

print (pd.DataFrame(df.values.reshape(-1, 5), 
                    columns=['Name','School','Music','Mentor1','Mentor2']))

Leave a Comment