1

I have a dataframe that has a redundant set of columns that I would like to get rid of. My actual use case is a bit convoluted, but the essence can be captured in the following:

my_frame = pd.DataFrame(data={'a':[1,1,3],'b':[7,8,9],'c':[4,5,6],
                              'subcolumn_1':['A1','A2','A3'],
                              'subcolumn_2':['B1','B2','B3']})
my_frame.set_index(keys=['subcolumn_1','subcolumn_2'], inplace=True)
my_frame.transpose()

i.e.

subcolumn_1 A1  A2  A3
subcolumn_2 B1  B2  B3
a   1   1   3
b   7   8   9
c   4   5   6

I would like to delete subcolumn_2. However, I cannot do so via the standard method (e.g. by a drop) because subcolumn_2 is a column header, not an actual row.

Daniel Marchand
  • 584
  • 8
  • 26

1 Answers1

0

try droplevel

my_frame.columns = my_frame.columns.droplevel(1)
Yuca
  • 6,010
  • 3
  • 22
  • 42
  • The code above does not work, but ```df.droplevel(0, axis=1) ``` does. See tagged question duplicate. – Daniel Marchand Aug 19 '19 at 13:45
  • well, I have the exact same code on my scripts an it works, so it is definitely strange. Just to be sure, if the dataframe you output is the transpose and not `my_frame` itself, then add the line `my_frame= my_frame.T` – Yuca Aug 19 '19 at 13:50