0

I have a dataframe in Pandas, which looks like this:

metric all_areas area_1 area_2
team_1_count 30 31 31
team_1_sum 1146 536 308
team_2_count 38 38 41
team_2_sum 1146 536 308

I need to transform the table to be like this:

desirable result

is there any way to make it? Is it even possible in Pandas? Example data is weird because it is fake and does not make sense.

Daniel G
  • 41
  • 6
  • 1
    `split` the metric columns in two (`df[['metric', 'col']] = df['metric'].str.rsplit('_', n=1, expand=True)`) and `pivot` or `unstack`. – mozway Jul 17 '23 at 08:38
  • @mozway can you please clarify a little? what does it mean to split the metric column? why? – Daniel G Jul 17 '23 at 08:41
  • 1
    You have many different ways to do this, here is one: `out = df.drop(columns='metric').join(df['metric'].str.rsplit('_', n=1, expand=True)).pivot(index=0, columns=1).rename_axis(index=None, columns=[None, None])` Please read the duplicate, read the [doc](https://pandas.pydata.org/docs/user_guide/reshaping.html), and search SO on `pivot`/`stack`/`unstack`, this is one of the most frequently asked pandas question. – mozway Jul 17 '23 at 08:45

0 Answers0