Index Column Position

Viewed 149


How to fix a "Pandas Data Frame" at which,
"Index Column" set to be shown at the Right hand side of the others,
instead of the default left one.

1 Answers

approaches

  • drop the index and concat() to RHS
  • add javascript to to_html() that moves attributes change column order. This doesn't work well with jupyter as javascript is not executed
df = pd.DataFrame({"idxcol":["A","B","C"], "idxcol2":["N","M","N"],"col2":[1,2,3]}).set_index(["idxcol","idxcol2"])
dfr = pd.concat([df.reset_index(drop=True), pd.Series(df.index.values)], axis=1).rename(columns={0:"-".join(df.index.names)})

print(df.to_markdown())
print(dfr.to_markdown())

before

                col2
idxcol idxcol2      
A      N           1
B      M           2
C      N           3

after

   col2 idxcol-idxcol2
0     1         (A, N)
1     2         (B, M)
2     3         (C, N)
Related