[英]How to find the difference between hour of day of separate days in a pandas dataframe?
對於沒有缺失值的數據幀,這將像df.diff(periods=24, axis=0)
一樣簡單df.diff(periods=24, axis=0)
。 但是如何將計算連接到指數值呢?
可重復的數據幀 - 代碼:
# Imports
import pandas as pd
import numpy as np
# A dataframe with two variables, random numbers and hourly time series
np.random.seed(123)
rows = 36
rng = pd.date_range('1/1/2017', periods=rows, freq='H')
df = pd.DataFrame(np.random.randint(100,150,size=(rows, 2)), columns=['A', 'B'])
df = df.set_index(rng)
可重復的數據框 - 屏幕截圖:
期望的輸出 - 代碼:
# Running difference step = 24
df = df.diff(periods=24, axis=0)
df = df.dropna(axis=0, how='all')
期望的輸出 - 截圖
真正的挑戰
問題是我的真實世界的例子充滿了缺失值。 所以我必須將差異區間與索引值聯系起來,我不知道如何。 我已經嘗試了一些解決方案,首先填寫索引中缺少的小時數,然后像以前一樣運行差異,但它不是很優雅。
謝謝你的任何建議!
編輯 - 根據評論中的要求,這是我嘗試更長時間的最佳嘗試:
df_missing = df.drop(df.index[[2,3]])
newIndex = pd.date_range(start = '1/1/2017', end = '1/3/2017', freq='H')
df_missing = df_missing.reindex(newIndex, fill_value = np.nan)
df_refilled = df_missing.diff(periods=24, axis=0)
相比其他建議,我會說這不是很優雅=)
您可以使用asfreq
將數據幀捕捉到每小時錄制,然后使用diff
?
df.asfreq('1H').diff(periods=24, axis=0).dropna()
或者,使用shift
然后減去(而不是diff
),
v = df.asfreq('1h')
(v - v.shift(periods=24)).dropna()
A B
2017-01-02 00:00:00 -3.0 3.0
2017-01-02 01:00:00 -28.0 -23.0
2017-01-02 02:00:00 -4.0 -7.0
2017-01-02 03:00:00 3.0 -29.0
2017-01-02 04:00:00 -4.0 3.0
2017-01-02 05:00:00 -17.0 -6.0
2017-01-02 06:00:00 -20.0 35.0
2017-01-02 07:00:00 -2.0 -40.0
2017-01-02 08:00:00 13.0 -21.0
2017-01-02 09:00:00 -9.0 -13.0
2017-01-02 10:00:00 0.0 3.0
2017-01-02 11:00:00 -21.0 -9.0
我想也許你可以使用groupby
df.groupby(df.index.hour).diff().dropna()
Out[784]:
A B
2017-01-02 00:00:00 -3.0 3.0
2017-01-02 01:00:00 -28.0 -23.0
2017-01-02 02:00:00 -4.0 -7.0
2017-01-02 03:00:00 3.0 -29.0
2017-01-02 04:00:00 -4.0 3.0
2017-01-02 05:00:00 -17.0 -6.0
2017-01-02 06:00:00 -20.0 35.0
2017-01-02 07:00:00 -2.0 -40.0
2017-01-02 08:00:00 13.0 -21.0
2017-01-02 09:00:00 -9.0 -13.0
2017-01-02 10:00:00 0.0 3.0
2017-01-02 11:00:00 -21.0 -9.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.