简体   繁体   中英

How to remove multi index from dataframe in python?

I have a data frame

          purchase_count
Scrips     1STCUS  20MICRONS  21STCENMGM  3MINDIA
Client_id                   
A100027     NaN      NaN        NaN         NaN 
A100074     NaN      NaN        NaN         NaN 
A100077     NaN      NaN        NaN         NaN
A100088     NaN      NaN        NaN         NaN 
A100091     NaN      NaN        NaN         NaN

This dataframe is a result of pd.pivot_table and is getting created as multi index .Also output of df_matrix.columns is

MultiIndex(levels=[['purchase_count'], ['1STCUS', '20MICRONS', '21STCENMGM', '3IINFOTECH', '3MINDIA']])

How to remove multi indexing in which I want my output to be

            1STCUS  20MICRONS  21STCENMGM  3MINDIA                  
A100027     NaN      NaN        NaN         NaN 
A100074     NaN      NaN        NaN         NaN 
A100077     NaN      NaN        NaN         NaN
A100088     NaN      NaN        NaN         NaN 
A100091     NaN      NaN        NaN         NaN

You can use MultiIndex.droplevel :

df.columns = df.columns.droplevel(0)

Another solution should be changed pivot_table , obviosly remove [] around ['purchase_count']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM