Home > Enterprise >  Resetting all indices from multiple index dataframe
Resetting all indices from multiple index dataframe

Time:06-18

I have a multi-index dataframe (df):

contract             A               B                    Total 
sex     Male    Female  Male    Female  TotalMale   TotalFemale
grade2                      
B1       948       467   408       835       1356          1302
B2       184       863   515       359        699          1222
B3       241       351   907       360       1148           711
B4       472       175   809       555       1281           730
B5       740       563   606       601       1346          1164
B6       435       780   295       392        730          1172
Total   3020      3199  3540      3102       6560          6301

I am trying to drop all indexes so my output is:

           0         1     2         3          4             5
0        948       467   408       835       1356          1302
1        184       863   515       359        699          1222
2        241       351   907       360       1148           711
3        472       175   809       555       1281           730
4        740       563   606       601       1346          1164
5        435       780   295       392        730          1172
6       3020      3199  3540      3102       6560          6301

I have tried:

df= df.reset_index()
and
df= df.reset_index(drop=True)

without success

CodePudding user response:

Try with build newDataFrame

df = pd.DataFrame(df.to_numpy())

CodePudding user response:

You can use set_axis for the columns:

df.set_axis(range(df.shape[1]), axis=1).reset_index(drop=True)

If you need to use it in a pipeline, combine it with pipe:

(df
.pipe(lambda d: d.set_axis(range(d.shape[1]), axis=1))
.reset_index(drop=True)
)
  • Related