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.

0

1 Answer 1

0

try droplevel

my_frame.columns = my_frame.columns.droplevel(1)
Sign up to request clarification or add additional context in comments.

2 Comments

The code above does not work, but df.droplevel(0, axis=1) does. See tagged question duplicate.
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.