我有以下数据帧,其中每小时的温度在不同的坐标下:
df.head
Out[63]:
time latitude longitude t2m
2018-01-01 00:00:00 72.0 -11.0 -3.957336
2018-01-01 01:00:00 72.0 -11.0 -4.165466
2018-01-01 02:00:00 72.0 -11.0 -4.562500
2018-01-01 03:00:00 72.0 -11.0 -4.860107
2018-01-01 04:00:00 72.0 -11.0 -5.155762
... ... ...
2018-12-31 19:00:00 34.0 32.0 16.527161
2018-12-31 20:00:00 34.0 32.0 16.639832
2018-12-31 21:00:00 34.0 32.0 16.700165
2018-12-31 22:00:00 34.0 32.0 16.592102
2018-12-31 23:00:00 34.0 32.0 16.724670
我想找到每对坐标的每日平均温度。为此,我需要每24行进行分组并找到t2m
列的均值,同时在time
列和latitude
andlongitude
列中保留唯一的日期。那是,
df.head
Out[63]:
time latitude longitude t2m
2018-01-01 72.0 -11.0 -6.378744
2018-01-01 71.75 -11.0 -5.564683
... ... ...
2018-12-31 33.75 31.75 16.836736
2018-12-31 34.0 32.0 16.836736
我试着做
N=24
test=df.groupby(df.index//N).mean()
但是我知道了TypeError: cannot perform __floordiv__ with this index type: DatetimeIndex
。我尝试重置索引并重复该操作,但是time
在添加其余部分时会删除该列。
最好的方法是什么?任何帮助将非常感激。先感谢您。
编辑:使用@Shubham Sharma的建议,我尝试做
df.reset_index(inplace=True)
N=24
test=df.groupby([df.index//N, 'latitude', 'longitude']).mean()
它会找到正确的平均值,但会完全删除该time
列。
通常,它使用起来更简单,更通用pd.Grouper(freq='D')
。
从您的数据片段中,尚不清楚您的数据框是否具有索引。如果有,那么df.head()
(而不是df.head
BTW)将显示:
latitude longitude t2m
time <--- notice the new line
2018-01-01 00:00:00 72.0 -11.0 -3.957336
2018-01-01 01:00:00 72.0 -11.0 -4.165466
2018-01-01 02:00:00 72.0 -11.0 -4.562500
2018-01-01 03:00:00 72.0 -11.0 -4.860107
2018-01-01 04:00:00 72.0 -11.0 -5.155762
如果没有,df.head()
则将显示默认值RangeIndex
:
time latitude longitude t2m
0 2018-01-01 00:00:00 72.0 -11.0 -3.957336
1 2018-01-01 01:00:00 72.0 -11.0 -4.165466
2 2018-01-01 02:00:00 72.0 -11.0 -4.562500
3 2018-01-01 03:00:00 72.0 -11.0 -4.860107
4 2018-01-01 04:00:00 72.0 -11.0 -5.155762
在任一情况下:
如果time
是索引,则:
out = df.groupby([pd.Grouper(freq='D'), 'latitude', 'longitude']).mean()
# out:
t2m
time latitude longitude
2018-01-01 72.0 -11.0 -4.540234
如果time
只是常规列:
out = df.groupby([pd.Grouper(key='time', freq='D'), 'latitude', 'longitude']).mean()
# out:
t2m
time latitude longitude
2018-01-01 72.0 -11.0 -4.540234
在这两种情况下,您都可以将结果从具有MultiIndex
变为表型数据框:
out = out.reset_index()
# out:
time latitude longitude t2m
0 2018-01-01 72.0 -11.0 -4.540234
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句