1

I have a challenge in front of me in python.

| Growth_rate  | Month |
| ------------ |-------|
|            0 |     1 | 
|           -2 |     1 | 
|          1.2 |     1 | 
|          0.3 |     2 | 
|         -0.1 |     2 | 
|            7 |     2 | 
|            9 |     3 | 
|          4.1 |     3 |

Now I want to average the growth rate according to the months in a new columns. Like 1st month the avg would be -0.26 and it should look like below table.

| Growth_rate | Month | Mean  |
| ----------- | ----- | ----- |
|           0 |     1 | -0.26 |
|          -2 |     1 | -0.26 |
|         1.2 |     1 | -0.26 |
|         0.3 |     2 |   2.2 |
|        -0.1 |     2 |   2.2 |
|           7 |     2 |   2.2 |
|           9 |     3 |   6.5 |
|         4.1 |     3 |   6.5 |

This will calculate the mean growth rate and put it into mean column.

Any help would be great.

kentwait
  • 1,969
  • 2
  • 21
  • 42
Parth Dhir
  • 11
  • 7

2 Answers2

2
df.groupby(df.months).mean().reset_index().rename(columns={'Growth_Rate':'mean'}).merge(df,on='months')
Out[59]: 
   months      mean  Growth_Rate
0       1 -0.266667          0.0
1       1 -0.266667         -2.0
2       1 -0.266667          1.2
3       2  2.200000         -0.3
4       2  2.200000         -0.1
5       2  2.200000          7.0
6       3  6.550000          9.0
7       3  6.550000          4.1
Onyambu
  • 67,392
  • 3
  • 24
  • 53
0

Assuming that you are using the pandas package. If your table is in a DataFrame df

In [91]: means = df.groupby('Month').mean().reset_index()
In [92]: means.columns = ['Month', 'Mean']

Then join via merge

In [93]: pd.merge(df, means, how='outer', on='Month')
Out[93]:
   Growth_rate  Month      Mean
0          0.0      1 -0.266667
1         -2.0      1 -0.266667
2          1.2      1 -0.266667
3          0.3      2  2.400000
4         -0.1      2  2.400000
5          7.0      2  2.400000
6          9.0      3  6.550000
7          4.1      3  6.550000
kentwait
  • 1,969
  • 2
  • 21
  • 42