Home > Back-end >  How to drop one level of a multiindex in pandas
How to drop one level of a multiindex in pandas

Time:07-28

Im trying to drop a level of my multi index using drop, but I cant get it to work.

iterables = [["bar", "baz"], ["bar", "baz"]]
index = pd.MultiIndex.from_product(iterables, names=["first", "second"])
df = pd.Series([1, 2, 3, 4], index=index) 
df

df looks like this:

first  second
bar    one       1
       two       2
baz    one       3
       two       4

I want to drop the second level of the multi index, so that I would have as result:

first
bar    1
bar    2
baz    3
baz    4

However, df.drop(index=['second']) and df.drop(index=['second'],level=1) dont work, so Im a little confused on how to get it done.

CodePudding user response:

you use pd.MultiIndex.droplevel

df=df.droplevel(level=1)

or

df=df.droplevel('second')

df
first
bar    1
bar    2
baz    3
baz    4
dtype: int64
  • Related