【问题标题】:Remove double row column names from a pivot result从数据透视结果中删除双行列名称
【发布时间】:2020-06-16 19:03:15
【问题描述】:

我想删除一个数据透视结果的“双行”索引标题,所以下表:

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')

【问题讨论】:

  • 是的,在我问之前我找不到类似的问题。谢谢@anky。我应该删除我的问题吗?

标签: pandas


【解决方案1】:

你可以的

result.columns.name = None

【讨论】:

    【解决方案2】:

    使用DataFrame.rename_axis 删除columns name,此处使用Course_ID,然后使用DataFrame.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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-18
      • 2018-07-26
      • 2016-03-27
      • 2011-09-07
      相关资源
      最近更新 更多