Home > OS >  How to convert level 2 indexes to be columns index dataframe with pandas or etc
How to convert level 2 indexes to be columns index dataframe with pandas or etc

Time:06-30

my first dataframe is like this:

value
idx1 idx2
1 a 9
b 8
2 a 7
b 6

i want to convert into like this:

idx1 a b
1 9 8
2 7 6

CodePudding user response:

Assuming a MultiIndex, you need to convert to Series and unstack:

df['value'].unstack('idx2').reset_index().rename_axis(None, axis=1)

output:

   idx1  a  b
0     1  9  8
1     2  7  6

used input:

df = (pd.DataFrame({'value': {(1, 'a'): 9, (1, 'b'): 8, (2, 'a'): 7, (2, 'b'): 6}})
        .rename_axis(['idx1', 'idx2'])
      )
  • Related