![](/img/trans.png)
[英]Transpose every nth rows from one column to multiple columns using pandas
[英]Transpose the data in a column every nth rows in PANDAS
對於研究項目,我需要將網站上每個人的信息都處理成一個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
除以列數生成新array
的length
的更通用的解決方案:
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']))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.