Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove levels from a multi-indexed dataframe?

For example, I have:

In [1]: df = pd.DataFrame([8, 9],                           index=pd.MultiIndex.from_tuples([(1, 1, 1),                                                            (1, 3, 2)]),                           columns=['A'])  In [2] df Out[2]:         A 1 1 1  8   3 2  9 

Is there a better way to remove the last level from the index than this:

In [3]: pd.DataFrame(df.values,                      index=df.index.droplevel(2),                      columns=df.columns) Out[3]:       A 1 1  8   3  9 
like image 797
Yariv Avatar asked Jun 13 '13 10:06

Yariv


People also ask

How do you remove indices from a data frame?

The most straightforward way to drop a Pandas dataframe index is to use the Pandas . reset_index() method. By default, the method will only reset the index, forcing values from 0 - len(df)-1 as the index. The method will also simply insert the dataframe index into a column in the dataframe.

How do you unset an index?

Use DataFrame.reset_index() function We can use DataFrame. reset_index() to reset the index of the updated DataFrame. By default, it adds the current row index as a new column called 'index' in DataFrame, and it will create a new row index as a range of numbers starting at 0.

How do I change the index level in pandas?

To change the index values we need to use the set_index method which is available in pandas allows specifying the indexes. where, inplace parameter accepts True or False, which specifies that change in index is permanent or temporary. True indicates that change is Permanent.


1 Answers

df.reset_index(level=2, drop=True) Out[29]:       A 1 1  8   3  9 
like image 94
Yariv Avatar answered Oct 12 '22 22:10

Yariv