The dataframe in pandas looks like that:
I need to rename them correspondingly to
buy_1
, buy_2
, buy_3
, ... sell_1
, sell_2
What is the most efficient way to do it?
CodePudding user response:
You can try with format
df.columns = df.columns.map('{0[0]}_{0[1]}'.format)
CodePudding user response:
Try:
df.set_axis(df.columns.map('_'.join),axis=1)
If your second level is int
and not str
, either of the below would work with still using join()
.
df.set_axis(df.columns.map(lambda x: '_'.join([str(i) for i in x])),axis=1)
df.set_axis(df.columns.set_levels(df.columns.levels[1].astype(str),level=1).map('_'.join),axis=1)