python - 如何在Python中对月份列进行排序后找到平均值

标签 python python-3.x jupyter-notebook jupyter data-science-experience

我在Python方面面临着挑战。

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

现在我想根据新列中的月份来平均增长率。就像第一个月一样,平均值将为 -0.26,它应该如下表所示。

| 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 |

这将计算平均增长率并将其放入平均值列中。

任何帮助都会很棒。

最佳答案

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

关于python - 如何在Python中对月份列进行排序后找到平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54391002/

相关文章:

python - 检查一组坐标与另一组坐标的接近程度

python - PyQt5 使用 runJavaScript 检索表单值

python - 是否有任何包可以在Azure中使用python编程将doc文件转换为docx格式?

python - 在 Python 中创建数字日期/时间表示

r - 在 jupyter notebook 中在 R 和 Python 之间共享变量

python - 不能定义 2 是否为质数

python - url调度中找到favicon.ico的 Pyramid 路由,但同时遍历没有找到

javascript - 使用网站输入运行 python 脚本

python - 如何在 Sphinx 处理的文档字符串中表示单个参数或返回值的多种类型?

bash - 无法连接到 Docker 提供的 Jupyter Notebook