从数据透视表结果中删除双行列名称

伊万·维里亚迪(Ivan Wiryadi)

我想删除数据透视结果的“双行”索引标头,因此下表如下:

Course_ID   CID-1   CID-2   CID-3
ID          
1           3.5     2.0     3.0
2           4.0     3.0     NaN

看起来像这样:

ID          CID-1   CID-2   CID-3           
1           3.5     2.0     3.0
2           4.0     3.0     NaN

我该如何实现?

这是示例代码:

sample = pd.DataFrame({'ID': [1, 1, 1, 2, 2], 
                       'Course_ID': ['CID-1', 'CID-2', 'CID-3', 'CID-1', 'CID-2'], 
                       'Grade': [3.5, 2, 3, 4, 3]})

result = pd.pivot_table(sample, index='ID', columns='Course_ID', values='Grade')
耶斯列尔

使用DataFrame.rename_axis了删除columns name,这里Course_IDDataFrame.reset_index为转换索引列ID

result = result.rename_axis(None, axis=1).reset_index()
print (result)
   ID  CID-1  CID-2  CID-3
0   1    3.5    2.0    3.0
1   2    4.0    3.0    NaN

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章