Это будет делать:
new_df = (df.reset_index(level=1, drop=True)
.set_index(df.groupby(level=0).cumcount(), append=True) # this is your step 1
.unstack(level=1)
)
# rename columns
new_df.columns = [f'{x}_{y}' for x,y in new_df.columns]
# reset_index
new_df = new_df.reset_index()
Пример данных:
df = (pd.DataFrame({'a':['x']*4+['y']*3,
'b':[8,8,8,9,7,7,7],
'A':[1,2,3,4,5,6,7],
'B':[7,6,5,4,3,2,1]})
.set_index(['a','b'])
)
Выход:
a A_0 A_1 A_2 A_3 B_0 B_1 B_2 B_3
0 x 1.0 2.0 3.0 4.0 7.0 6.0 5.0 4.0
1 y 5.0 6.0 7.0 NaN 3.0 2.0 1.0 NaN