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
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.
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.
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.
df.reset_index(level=2, drop=True) Out[29]: A 1 1 8 3 9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With