[英]Is there a pandas function to transpose a data frame to create a separate column for each unique value of an existing column?
[英]How to transpose pandas data frame by a column and value?
我有一個這樣的數據框
輸入
student_id rep
abc100 1
abc101 2
abc102 1
abc103 2
abc104 1
abc105 2
abc106 1
abc107 2
預期產量
1 2
abc100 abc101
abc102 abc103
abc104 abc105
abc106 abc107
我試過了
df = df.pivot( columns='rep', values='student_id')
但是它包含很多難解的問題,並且沒有給出預期的輸出。
我在stackoverflow中進行了搜索,但找不到答案。
為了匹配所需的確切輸出,您可以執行
df['aux'] = df.groupby('rep').cumcount()
df.pivot(index='aux' ,columns='rep', values='student_id')
輸出:
rep 1 2
aux
0 abc100 abc101
1 abc102 abc103
2 abc104 abc105
3 abc106 abc107
您可以通過使用iloc和arg步驟對列進行切片來選擇df:
>>> pd.DataFrame({'student_id':df['student_id'].iloc[::2].values, 'student_id_1':df['student_id'].iloc[1::2].values})
student_id student_id_1
0 abc100 abc101
1 abc102 abc103
2 abc104 abc105
3 abc106 abc107
或,@coldspeed提出的另一種建議只是為了提高可視性:-)
df.assign(index=df.groupby('rep').cumcount()).pivot('index', 'rep', 'student_id')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.