在PANDAS中,每隔n行转换一次列中的数据

9

为了一个研究项目,我需要将网站上每个人的信息处理成一个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

什么是最有效的方法来完成这个任务?
1个回答

15

如果没有数据丢失,你可以使用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']))

4
pd.DataFrame(df.values.reshape(-1, 5), columns=['Name','School','Music','Mentor1','Mentor2'])) - piRSquared
非常感谢@jezrael和@piRSquared! - Molly Zhao

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