0

I have the following pandas dataframe:

    time  mes   mech
0   1     50    A
1   2     15    A
2   3     16    A
3   1     17    B
4   2     49    B
5   3     62    B

I would like to aggregate it by time and then have the renamed columns for each mech, like so:

    time  mes_A mes_B
0   1     50    17
1   2     15    49
2   3     16    62

what's the best way to do this?

apocalypsis
  • 520
  • 8
  • 19

2 Answers2

2
out = (df.pivot('time', 'mech', 'mes')
         .add_prefix('mech_')
         .reset_index())
out.columns.name = None
print(out)

Output:

   time  mech_A  mech_B
0     1      50      17
1     2      15      49
2     3      16      62
BeRT2me
  • 12,699
  • 2
  • 13
  • 31
2

You can do it like this:

df = pd.DataFrame({"time": [1, 2, 3, 1, 2, 3], "mes": [50, 15, 16, 17, 49, 62], "mech": ["A", "A", "A", "B", "B", "B"]})


def agg_mech(row):
    return {f"mech_{v}": v for v in row}

df2 = df.groupby("time").agg({"mes": "first", "mech": agg_mech})
df2 = df2.merge(df2.mech.apply(pd.Series), left_index=True, right_index=True).drop(columns=["mech"])
eightlay
  • 423
  • 2
  • 9