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

时间:2018-12-17 16:10:21

标签: python pandas pivot-table series transpose

我有一个这样的数据框

输入

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,并且没有给出预期的输出。

我在stackoverflow中进行了搜索,但找不到答案。

2 个答案:

答案 0 :(得分:3)

要完全匹配所需的输出,您可以

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

答案 1 :(得分:0)

您可以通过使用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

OR,另一种方式@coldspeed建议只是为了提高可视性:-)

df.assign(index=df.groupby('rep').cumcount()).pivot('index', 'rep', 'student_id')