1

I'd like to remove a 'double row' index header of a pivot result, so the following table:

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

would look like this:

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

How may I achieve this?

Here's the sample code:

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')
strivn
  • 309
  • 2
  • 8
  • [very related to this](https://stackoverflow.com/questions/43756052/transform-pandas-pivot-table-to-regular-dataframe) – anky Jun 16 '20 at 05:34
  • ah true, I couldn't find similar questions before I asked. Thank you @anky. Should i delete my question? – strivn Jun 16 '20 at 05:45

2 Answers2

7

You can do

result.columns.name = None
FlorianGD
  • 2,336
  • 1
  • 15
  • 32
0

Use DataFrame.rename_axis for remove columns name, here Course_ID and then DataFrame.reset_index for convert index to column 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
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252