Reputation: 4753
I've a dataframe with row and column multiindex like this
BLUB BLA
A B C D
sample
0 blub ... ...
1 blub ...
2 blub
3 blub
4 blub
0 blub
1 blub
2 blub
... ...
I'd like to reindex to this
BLUB BLA
A B C D
sample
0 blub ... ...
1 blub ...
2 blub
3 blub
4 blub
5 blub
6 blub
7 blub
... ...
in a immutable manner (copying the dataframe, not changing it in place). How can I achieve this?
Upvotes: 1
Views: 62
Reputation: 863801
Because MultiIndex in index
you can create default index by first level of MultiIndex
by DataFrame.reset_index
and DataFrame.set_index
:
df = (df.reset_index(level=1)
.reset_index(drop=True)
.set_index('level_1', append=True)
.rename_axis(['sample', None]))
Or by MultiIndex.from_arrays
:
mux = pd.MultiIndex.from_arrays([np.arange(len(df)),
df.index.get_level_values(1)],
names=['sample', None])
df = df.set_index(mux)
Upvotes: 1