在PANDAS中每隔第n行传输一列中的数据



对于一个研究项目,我需要将每个人的信息从网站处理到excel文件中。我已经从网站上复制并粘贴了我需要的所有内容到excel文件的一列中,并使用PANDAS加载了该文件。然而,我需要横向呈现每个人的信息,而不是像现在这样纵向呈现。例如,这就是我现在所拥有的。我只有一列没有组织的数据。

df= pd.read_csv("ior work.csv", encoding = "ISO-8859-1")

数据:

0 Andrew
1 School of Music
2 Music: Sound of the wind
3 Dr. Seuss
4 Dr.Sass
5 Michelle
6 School of Theatrics
7 Music: Voice
8 Dr. A
9 Dr. B

我想每隔5行转换一次,将数据组织成这种组织格式;下面的标签是列的标签。

Name School Music Mentor1 Mentor2

最有效的方法是什么?

如果没有数据丢失,可以使用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除以列数生成新arraylength的更通用的解决方案:

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

相关内容

最新更新