I want to use dataframe values as column names and simplify the dataframe.
I tried df.stack() and then index.map('{0[0]}_{0[1]}'.format)
Input_df(Got this df by doing a groupby):
link price  date
 A     1    01/01
 A     2    01/02
 A     1.2  01/03
Desired_ouput:
link price_01/01 price_01/02 price_01/03
  A      1            2         1.2
                df.set_index(['link', 'date']).price.unstack().add_prefix('price_')
date  price_01/01  price_01/02  price_01/03
link                                       
A             1.0          2.0          1.2
                        You can try this using set_index and unstack, then using Python 3.6+ can you use f-string with list comprehension to flatten multiindex column headers.
df_out = df.set_index(['link', 'date']).unstack()
df_out.columns = [f'{i}_{j}' for i, j in df_out.columns]
df_out.reset_index()
Output:
  link  price_01/01  price_01/02  price_01/03
0    A          1.0          2.0          1.2
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With