Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to drop one level of a multiindex in pandas

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading