Home > Enterprise >  two header rows to one header row pandas
two header rows to one header row pandas

Time:02-04

Given a dataframe that looks like this:

            min     max      mean       std       wav
symbol
1000038  0.0110  0.0022  0.003296 -0.002611  0.005514
1000043  0.0090  0.0102  0.004124 -0.000507  0.004847
1000055  0.0100  0.0030  0.001358 -0.001719  0.004363
1000059  0.0050  0.0017  0.003372 -0.001089  0.008595
1000060  0.0012  0.0062  0.002367  0.000407  0.006935

The rows headers are on two different rows, but are not multi-index as far as i am aware, so when i try to columns.droplevel(0) this fails with the error: Cannot remove 1 levels from an index with 1 levels: at least one level must be left.

The same csv file looks flat, like the below (but wish to avoid writing and reading back a csv) to correct the format.

symbol      min     max      mean       std       wav
1000038  0.0110  0.0022  0.003296 -0.002611  0.005514
1000043  0.0090  0.0102  0.004124 -0.000507  0.004847
1000055  0.0100  0.0030  0.001358 -0.001719  0.004363
1000059  0.0050  0.0017  0.003372 -0.001089  0.008595
1000060  0.0012  0.0062  0.002367  0.000407  0.006935

so my question is how to turn the above into a tidy (square) shape like the above with just one header row ?

CodePudding user response:

You can convert index with level symbol to column by enter image description here

Same thing without the index name (df.rename_axis(None)):

enter image description here

and after reset_index, the index becomes a column and a new (range) index appears

enter image description here

  •  Tags:  
  • Related