Home > front end >  Pandas Multiindex: convert Multiindex to a column and keep the first level hidden or as nan
Pandas Multiindex: convert Multiindex to a column and keep the first level hidden or as nan

Time:05-22

Here is my dataframe of Multiindex:

data3 = [['a', 'b',3,3],['a','c',3,3],['b','c',3,3],['c','d',3,3]]
df3 = pd.DataFrame(data3, columns=['v3a','v3b','v3c','v3d'])
df3 = df3.groupby(['v3a','v3b']).first()

How to convert Multiindex to a column and keep the first level hidden or as nan as following:

enter image description here

CodePudding user response:

To have NaN:

import numpy as np

df3 = df3.groupby(['v3a','v3b']).first().reset_index()
df3.loc[df3['v3a'].duplicated(), 'v3a'] = np.nan
print(df3)
   v3a v3b  v3c  v3d
0    a   b    3    3
1  NaN   c    3    3
2    b   c    3    3
3    c   d    3    3

If you mean "hidden" as in "empty string" you can do:

df3 = df3.groupby(['v3a','v3b']).first().reset_index()
df3.loc[df3['v3a'].duplicated(), 'v3a'] = ''
print(df3)
  v3a v3b  v3c  v3d
0   a   b    3    3
1       c    3    3
2   b   c    3    3
3   c   d    3    3
  • Related