gpt4 book ai didi

python - 如何按时间分组并做(并且只保留)Dataframe 中最后 3 个元素的平均值

转载 作者:太空宇宙 更新时间:2023-11-04 11:12:05 28 4
gpt4 key购买 nike

我有这个 Python 的 DataFrame :

temperature time
10.196833 01-03-2019 00:00:00
11.084986 01-03-2019 00:00:00
10.196833 01-03-2019 00:00:00
10.18458 01-03-2019 00:00:00
10.397547 01-03-2019 00:00:00
10.397547 01-03-2019 00:00:00
9.675623 01-03-2019 01:00:00
10.382349 01-03-2019 01:00:00
9.675623 01-03-2019 01:00:00
9.609171 01-03-2019 01:00:00
9.901361 01-03-2019 01:00:00
9.901361 01-03-2019 01:00:00
8.960459 01-03-2019 02:00:00
10.513941 01-03-2019 02:00:00
8.960459 01-03-2019 02:00:00
10.213129 01-03-2019 02:00:00
9.446863 01-03-2019 02:00:00
9.446863 01-03-2019 02:00:00

一天只有 3 个小时(00:00 到 02:00)我想只保留每小时的最后 3 行,并对其进行 GroupBy 平均,以仅获得每小时最后 3 个元素的平均值:

temperature time
10.326558 01-03-2019 00:00:00
9.8039643 01-03-2019 01:00:00
9.702285 01-03-2019 02:00:00

我试过了:

dataframe = df.groupby(time).apply(lambda x: x.iloc[[-3]]).mean 

但是我刚得到一个错误

最佳答案

你很接近。
此行提供所需的输出:

ddf = df.groupby('time').apply(lambda x : x.iloc[-3:].mean())

ddf 导致:

                     temperature
time
2019-01-03 00:00:00 10.326558
2019-01-03 01:00:00 9.803964
2019-01-03 02:00:00 9.702285

要使用最后 3 行,您需要切片,您忘记了 :。还有一对额外的括号,iloc 通常不需要。

关于python - 如何按时间分组并做(并且只保留)Dataframe 中最后 3 个元素的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57955098/

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