繁体   English   中英

如何按列和值转置熊猫数据帧?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM