1

I have the following data

   ---+--
    b | c
--+---+--
a
--+---+-- 
0 | 1 | 2
1 | 3 | 4

I would like to drop the level of column a and have the following as output:

--+---+--
 a| b | c
--+---+--
0 | 1 | 2
1 | 3 | 4

I have tried df.droplevel(1) but got the following error:

IndexError: Too many levels: Index has only 1 level, not 2

Any help is appreciated.

Ben.T
  • 29,160
  • 6
  • 32
  • 54
  • 2
    You have a simple Index on the columns, but have a named Index, so it is displayed that way. See my answer https://stackoverflow.com/a/55028542/4333359 that illustrates things are displayed when the row or columns index has a name. It allows you to avoid ambiguity. – ALollz Sep 03 '20 at 15:03
  • 1
    from the way you printed here, it looks more that a is the index, so `df.reset_index()` would kind of do what you want. to be sure, can you edit your question with the result of `print(df.index)` and `print(df.columns)` – Ben.T Sep 03 '20 at 15:03
  • @Ben.T : The out put for print(df.index) is Index([0,1]) and print(df.columns) is index(['b', 'c']) – Pulkit Jain Sep 03 '20 at 15:13
  • @Ben.T : My apologies: The output for print(df.index) is Index(['0','1'], dtype=dtype='object', name='a') – Pulkit Jain Sep 03 '20 at 15:23
  • so yes, I recommend go through the link provided by @ALollz in their comment, and as a is actually your index name, then you can either `rename_axis(None)` to make it disappeared or use `reset_index` such as `a` become a column and the display will be better :) – Ben.T Sep 03 '20 at 15:26
  • @ben-t : tried both `reset_index` and `rename_axis`, none of them is working. Getting same output. – Pulkit Jain Sep 03 '20 at 15:34
  • hmmm do you reassign it? if you `print( df.reset_index())` it does not work? what about `df = df.reset_index()` and then print df? – Ben.T Sep 03 '20 at 15:38
  • 1
    @Ben.T - Thanks Ben! reassigning the df, solved the problem. – Pulkit Jain Sep 03 '20 at 15:42
  • 1
    @alollz - Thanks, your solution and Ben's help solved the problem. – Pulkit Jain Sep 03 '20 at 15:45

1 Answers1

2

As suggested by @Alollz & @Ben, I did the following:

df = df.reset_index()

And got the following output

---+---+---+---+
   | a | b | c
---+---+---+---+--
 0 | 0 | 1 | 2
 1 | 1 | 3 | 4
Ben.T
  • 29,160
  • 6
  • 32
  • 54
  • 1
    Good idea to answer your question, you can also accept it to help the management of the site :) – Ben.T Sep 03 '20 at 17:47