You can subset the data (by ‘Type’ here), group the required subset and union them back.

import pandas as pd

df = pd.DataFrame({'type': [1, 1, 1, 1, 2, 2, 2, 2], 'value': [2, 3, 4, 1, 2, 4, 1, 1]})
df1 = df[df['type']==1]
df2 = df[df['type']==2]

df2_grouped = df2.groupby('type').mean().reset_index(False)

df_final = pd.concat([df1, df2_grouped])
df_final

  type  value
0   1   2
1   1   3
2   1   4
3   1   1
0   2   2

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top