![](/img/trans.png)
[英]Pandas resample on given (arbitrary) datetimeindex (using e.g. nearest)
[英]Python-pandas - Datetimeindex: What is the mosty pythonic strategy to analyse rolling with steps? (e.g. certain hours for each day)
我正在使用跨越幾年的每小時溫度數據的DateTimeIndex進行數據處理。 我想用了一天的20:00至次日 8:00之間,最低溫度添加一列。 白天的溫度-8:00至20:00-無關緊要。 結果可以是原始數據的每小時分辨率,也可以重新采樣為幾天。
我研究了許多策略來解決此問題,但是不確定最有效的方式(就主要的編碼效率和輔助計算效率而言)分別是這樣做的。 我想出了一些可能性:
df.index.hour
附加一個標簽為“ day”,“ night”的列,並使用group_by
或df.loc
查找最小值 df.between_time
( https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.between_time.html#pandas.DataFrame.between_time ),盡管我不確定日期是否會更改午夜會使這有點混亂。 原始df如下所示:
datetime temp
2009-07-01 01:00:00 17.16
2009-07-01 02:00:00 16.64
2009-07-01 03:00:00 16.21 #<-- minimum for the night 2009-06-30 (previous date since periods starts 2009-06-30 20:00)
... ...
2019-06-24 22:00:00 14.03 #<-- minimum for the night 2019-06-24
2019-06-24 23:00:00 18.87
2019-06-25 00:00:00 17.85
2019-06-25 01:00:00 17.25
我想得到這樣的東西(從20:00天到18:00天的最低溫度):
datetime temp
2009-06-30 23:00:00 16.21
2009-07-01 00:00:00 16.21
2009-07-01 01:00:00 16.21
2009-07-01 02:00:00 16.21
2009-07-01 03:00:00 16.21
... ...
2019-06-24 22:00:00 14.03
2019-06-24 23:00:00 14.03
2019-06-25 00:00:00 14.03
2019-06-25 01:00:00 14.03
或更簡潔:
datetime temp
2009-06-30 16.21
... ...
2019-06-24 14.03
使用base
選項resample
:
rs = df.resample('12h', base=8).min()
然后僅保留20:00的行:
rs[rs.index.hour == 20]
您可以將TimeGrouper
與freq=12h
和base=8
一起使用,從20:00-(+ day)08:00每12小時對數據幀進行分塊,
那么你可以只使用.min()
嘗試這個:
import pandas as pd
from io import StringIO
s = """
datetime temp
2009-07-01 01:00:00 17.16
2009-07-01 02:00:00 16.64
2009-07-01 03:00:00 16.21
2019-06-24 22:00:00 14.03
2019-06-24 23:00:00 18.87
2019-06-25 00:00:00 17.85
2019-06-25 01:00:00 17.25"""
df = pd.read_csv(StringIO(s), sep="\s\s+")
df['datetime'] = pd.to_datetime(df['datetime'])
result = df.sort_values('datetime').groupby(pd.Grouper(freq='12h', base=8, key='datetime')).min()['temp'].dropna()
print(result)
輸出:
datetime
2009-06-30 20:00:00 16.21
2019-06-24 20:00:00 14.03
Name: temp, dtype: float64
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.