dmeu dmeu - 22 days ago 17
Python Question

Method chaining solution to drop column level in pandas DataFrame

I am using lot's of method chaining when reshaping and querying data I have in pandas

DataFrames
. Sometimes additional and unnecessary levels for the in indices (rows) and columns are being created. If so, e.g. on the the index (row-axis) this is easily solved by using
DataFrame.reset_index()
:

df.query('some query')
.apply(cool_func)
.reset_index('unwanted_index_level',drop=True) # <====
.apply(another_cool_func)


The
reset_index
function allows one to continue chain methods and keep working with the
DataFrame
.

Nevertheless, I never found an equivalent solution for the column_axis. Is there any at all?

Answer

You can just stack the column (move it to the index) and call reset_index with drop=True, or you could write a reset_columns() method using the reset_index() one as a starting point (see frame.py#L2940)

df.query('some query')
   .apply(cool_func)
   .stack(level='unwanted_col_level_name')
   .reset_index('unwanted_col_level_name',drop=True)
   .apply(another_cool_func)