如何按列和值转置 pandas 数据框? [英] How to transpose pandas data frame by a column and value?
本文介绍了如何按列和值转置 pandas 数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的数据框
输入
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')
但它包含很多 nan 并且没有给出预期的输出.
but it contains lot of nans and didnt give expected output.
我在 stackoverflow 中搜索但找不到答案.
I searched in stackoverflow but couldnt find an answer.
推荐答案
要准确匹配您可以执行的所需输出
To match the exact desired output you could do
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
这篇关于如何按列和值转置 pandas 数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文