gpt4 book ai didi

python - Pandas/Numpy 的历史平均值

转载 作者:太空宇宙 更新时间:2023-11-04 00:10:40 25 4
gpt4 key购买 nike

我有以下 Pandas 数据框 (df):

2013-01-01   7
2013-01-02 4
2013-01-02 8
2013-01-08 8
2013-01-11 10
2013-01-12 7

根据这些数字(实际上是学校成绩),我想绘制一个描绘历史平均值的图表。

期望的输出:

2013-01-01   7.000000
2013-01-02 6.333333
2013-01-03 6.333333
2013-01-04 6.333333
2013-01-05 6.333333
2013-01-06 6.333333
2013-01-07 6.333333
2013-01-08 6.750000
2013-01-09 6.750000
2013-01-10 6.750000
2013-01-11 7.400000
2013-01-12 7.333333

df.expanding().mean() 给我:

2013-01-01  7.000000
2013-01-02 5.500000
2013-01-02 6.333333
2013-01-08 6.750000
2013-01-11 7.400000
2013-01-12 7.333333

这是接近的日期,但我想要介于两者之间的日期。

如果我在 1d 的间隔上执行 resample(即 df.expanding().mean().resample("1d")。 mean()),我明白了:

 2013-01-01  7.000000
2013-01-02 5.916667
2013-01-03 NaN
2013-01-04 NaN
2013-01-05 NaN
2013-01-06 NaN
2013-01-07 NaN
2013-01-08 6.750000
2013-01-09 NaN
2013-01-10 NaN
2013-01-11 7.400000
2013-01-12 7.333333

这里的问题是非唯一索引(两次 2013-01-02)。 (NaN 可以固定 :-))

如何获得所需的输出?

最佳答案

使用Resampler.last对于重复日期时间的最后一个值,然后通过前向填充替换缺失的行:

s = df.expanding().mean().resample("1d").last().ffill()
print (s)
2013-01-01 7.000000
2013-01-02 6.333333
2013-01-03 6.333333
2013-01-04 6.333333
2013-01-05 6.333333
2013-01-06 6.333333
2013-01-07 6.333333
2013-01-08 6.750000
2013-01-09 6.750000
2013-01-10 6.750000
2013-01-11 7.400000
2013-01-12 7.333333
Freq: D, Name: A, dtype: float64

关于python - Pandas/Numpy 的历史平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52555388/

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