Pandas 从透视结果中删除双行列名
我想删除透视结果的“双行”索引头,因此下表:Pandas 从透视结果中删除双行列名,pandas,Pandas,我想删除透视结果的“双行”索引头,因此下表: 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 N
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')
用于删除列名称
,此处为课程ID
,然后用于将索引转换为列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
用于删除列名称
,此处为课程ID
,然后用于将索引转换为列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
你能行
result.columns.name = None
你能行
result.columns.name = None
啊,没错,在我提问之前,我找不到类似的问题。谢谢你,安基。我应该删除我的问题吗?啊,是的,在我提问之前,我找不到类似的问题。谢谢你,安基。我应该删除我的问题吗?