0

In a dataframe, how to create a new column called z_mean, which is the mean of column z when grouping x and y?

data = [
    {'x':0.0, 'y':0.0, 'z':0.8},
    {'x':0.0, 'y':0.0, 'z':1.0},
    {'x':0.0, 'y':0.0, 'z':1.2},
    {'x':1.0, 'y':1.0, 'z':1.6},
    {'x':1.0, 'y':1.0, 'z':2.0},
    {'x':1.0, 'y':1.0, 'z':2.4},
]
df = pd.DataFrame(data)
Xavier M
  • 547
  • 3
  • 6
  • 13

1 Answers1

0

You can use:

df['z_mean'] = df.groupby(['x', 'y']).z.transform('mean')

Similarly, if you need the standard deviation, you can use:

df['z_std'] = df.groupby(['x', 'y']).z.transform('std')
Xavier M
  • 547
  • 3
  • 6
  • 13