簡體   English   中英

Python-pandas-Datetimeindex:分析步數滾動的最蟒蛇策略是什么? (例如每天某些時間)

[英]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-無關緊要。 結果可以是原始數據的每小時分辨率,也可以重新采樣為幾天。

我研究了許多策略來解決此問題,但是不確定最有效的方式(就主要的編碼效率和輔助計算效率而言)分別是這樣做的。 我想出了一些可能性:

  1. 根據df.index.hour附加一個標簽為“ day”,“ night”的列,並使用group_bydf.loc查找最小值
  2. 重新采樣至12h,然后每秒降低一次。 不確定如何使重采樣周期從20:00開始。
  3. 添加一個多索引-我想這與方法1類似,但是對於我要實現的目標來說有點過高。
  4. 使用df.between_timehttps://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.between_time.html#pandas.DataFrame.between_time ),盡管我不確定日期是否會更改午夜會使這有點混亂。
  5. 最后,有一些關於將滾動與步進參數結合在一起作為新的熊貓功能的討論: https : //github.com/pandas-dev/pandas/issues/15354

原始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]

您可以將TimeGrouperfreq=12hbase=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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM