2017-06-15 70 views
1

數據幀每天只包含幾個時間戳,我需要爲每個日期選擇最新的一個(而不是數值,時間戳本身)。東風看起來是這樣的:選擇每個日期的最後一個時間戳

       A  B  C 
2016-12-05 12:00:00+00:00 126.0 15.0 38.54 
2016-12-05 16:00:00+00:00 131.0 20.0 42.33 
2016-12-14 05:00:00+00:00 129.0 18.0 43.24 
2016-12-15 03:00:00+00:00 117.0 22.0 33.70 
2016-12-15 04:00:00+00:00 140.0 23.0 34.81 
2016-12-16 03:00:00+00:00 120.0 21.0 32.24 
2016-12-16 04:00:00+00:00 142.0 22.0 35.20 

我設法實現我需要什麼樣的定義如下功能:

def find_last_h(df,column): 
    newindex = [] 
    df2 = df.resample('d').last().dropna() 
    for x in df2[column].values: 
     newindex.append(df[df[column]==x].index.values[0]) 
    return pd.DatetimeIndex(newindex) 

與我指定用作過濾器使用的列值以獲得所需的時間戳。這裏的問題是在非唯一值的情況下,這可能無法按需要工作。

所用另一種方式是:

grouped = df.groupby([df.index.day,df.index.hour]) 
    grouped.groupby(level=0).last() 

,然後重建時間戳,但它是更冗長。什麼是聰明的方式?

回答

3

使用boolean indexingduplicatedfloor用於截斷times形成的遮掩:

idx = df.index.floor('D') 
df = df[~idx.duplicated(keep='last') | ~idx.duplicated(keep=False)] 
print (df) 
         A  B  C 
2016-12-05 16:00:00 131.0 20.0 42.33 
2016-12-14 05:00:00 129.0 18.0 43.24 
2016-12-15 04:00:00 140.0 23.0 34.81 
2016-12-16 04:00:00 142.0 22.0 35.20 

reset_index + set_index另一種解決方案:

df = df.reset_index().groupby([df.index.date]).last().set_index('index') 
print (df) 
         A  B  C 
index         
2016-12-05 16:00:00 131.0 20.0 42.33 
2016-12-14 05:00:00 129.0 18.0 43.24 
2016-12-15 04:00:00 140.0 23.0 34.81 
2016-12-16 04:00:00 142.0 22.0 35.20 

resamplegroupbydates只丟了次:

print (df.resample('1D').last().dropna()) 
       A  B  C 
2016-12-05 131.0 20.0 42.33 
2016-12-14 129.0 18.0 43.24 
2016-12-15 140.0 23.0 34.81 
2016-12-16 142.0 22.0 35.20 

print (df.groupby([df.index.date]).last()) 
       A  B  C 
2016-12-05 131.0 20.0 42.33 
2016-12-14 129.0 18.0 43.24 
2016-12-15 140.0 23.0 34.81 
2016-12-16 142.0 22.0 35.20 
+0

很好,謝謝!一個問題,就是| 〜idx.duplicated(keep = False)真的需要嗎?我得到正確的布爾數組已經沒有它! – marpis

+1

此代碼獲取所有唯一行。也許在你的真實數據不是,但如果使用你的樣本,3.沒有它的行將被刪除。 – jezrael

0

df.resample('24H',kind='period').last().dropna()

+0

不是,因爲失去了時間。 – jezrael

+0

你是什麼意思的失去時間? – suvy

+0

輸出只是沒有時間的日期。 – jezrael

相關問題