gpt4 book ai didi

python - 列组中的平均值

转载 作者:行者123 更新时间:2023-11-30 23:33:31 26 4
gpt4 key购买 nike

我有一个包含每月值的数据框,我想获得 3 个月组平均值的季度值我的数据是这样的(仅以前 9 个月为例)

month        01     02     03     04     05     06     07     08     09  \
year
2000 90.26 90.95 91.04 90.87 90.78 91.13 90.87 90.95 91.30
2000 87.89 89.68 90.10 90.27 90.53 90.87 89.93 91.30 91.98
2000 74.17 74.98 74.74 73.97 74.07 74.26 74.71 76.93 78.67
2000 NaN NaN NaN NaN NaN NaN NaN NaN NaN
2000 86.74 85.48 87.45 88.31 88.71 88.23 88.08 87.76 88.94

我想获得 Q1 作为 01,02,03 月份的平均值。我能做到:

 df['Q1']=(df['01']+df['02']+df['03'])/3

但我会遇到 Nan 的问题。

我可以计算三个月为一组的平均值吗?

最佳答案

您可以使用 loc 和 Mean 手动执行此操作:

In [11]: df.loc[:, ['01', '02', '03']]
Out[11]:
01 02 03
year
2000 90.26 90.95 91.04
2000 87.89 89.68 90.10
2000 74.17 74.98 74.74
2000 NaN NaN NaN
2000 86.74 85.48 87.45

In [12]: df.loc[:, ['01', '02', '03']].mean(axis=1)
Out[12]:
year
2000 90.750000
2000 89.223333
2000 74.630000
2000 NaN
2000 86.556667
dtype: float64

但使用 pandas' rolling_mean 可能更有意义:

In [21]: pd.rolling_mean(df.T, 3)
Out[21]:
year 2000 2000 2000 2000 2000
month
01 NaN NaN NaN NaN NaN
02 NaN NaN NaN NaN NaN
03 90.750000 89.223333 74.630000 NaN 86.556667
04 90.953333 90.016667 74.563333 NaN 87.080000
05 90.896667 90.300000 74.260000 NaN 88.156667
06 90.926667 90.556667 74.100000 NaN 88.416667
07 90.926667 90.443333 74.346667 NaN 88.340000
08 90.983333 90.700000 75.300000 NaN 88.023333
09 91.040000 91.070000 76.770000 NaN 88.260000

默认情况下,这会向后移动 3 个周期,因此我们必须将其向上移动两个周期:

In [22]: pd.rolling_mean(df.T, 3).shift(-2)
Out[22]:
year 2000 2000 2000 2000 2000
month
01 90.750000 89.223333 74.630000 NaN 86.556667
02 90.953333 90.016667 74.563333 NaN 87.080000
03 90.896667 90.300000 74.260000 NaN 88.156667
04 90.926667 90.556667 74.100000 NaN 88.416667
05 90.926667 90.443333 74.346667 NaN 88.340000
06 90.983333 90.700000 75.300000 NaN 88.023333
07 91.040000 91.070000 76.770000 NaN 88.260000
08 NaN NaN NaN NaN NaN
09 NaN NaN NaN NaN NaN

并转置为正确的形式:

In [23]: pd.rolling_mean(df.T, 3).shift(-2).T
Out[23]:
month 01 02 03 04 05 06 07 08 09
year
2000 90.750000 90.953333 90.896667 90.926667 90.926667 90.983333 91.04 NaN NaN
2000 89.223333 90.016667 90.300000 90.556667 90.443333 90.700000 91.07 NaN NaN
2000 74.630000 74.563333 74.260000 74.100000 74.346667 75.300000 76.77 NaN NaN
2000 NaN NaN NaN NaN NaN NaN NaN NaN NaN
2000 86.556667 87.080000 88.156667 88.416667 88.340000 88.023333 88.26 NaN NaN

关于python - 列组中的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18746244/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com