pandas的resample重采樣


Pandas中的resample,重新采樣,是對原樣本重新處理的一個方法,是一個對常規時間序列數據重新采樣和頻率轉換的便捷的方法。

降采樣:高頻數據到低頻數據

升采樣:低頻數據到高頻數據

主要函數:resample()(pandas對象都會有這個方法)

resample方法的參數

參數 說明
freq 表示重采樣頻率,例如‘M’、‘5min’,Second(15)
how=’mean’ 用於產生聚合值的函數名或數組函數,例如‘mean’、‘ohlc’、np.max等,默認是‘mean’,其他常用的值由:‘first’、‘last’、‘median’、‘max’、‘min’
axis=0 默認是縱軸,橫軸設置axis=1
fill_method = None 升采樣時如何插值,比如‘ffill’、‘bfill’等
closed = ‘right’ 在降采樣時,各時間段的哪一段是閉合的,‘right’或‘left’,默認‘right’
label= ‘right’ 在降采樣時,如何設置聚合值的標簽,例如,9:30-9:35會被標記成9:30還是9:35,默認9:35
loffset = None 面元標簽的時間校正值,比如‘-1s’或Second(-1)用於將聚合標簽調早1秒
limit=None 在向前或向后填充時,允許填充的最大時期數
kind = None 聚合到時期(‘period’)或時間戳(‘timestamp’),默認聚合到時間序列的索引類型
convention = None 當重采樣時期時,將低頻率轉換到高頻率所采用的約定(start或end)。默認‘end’

首先創建一個Series,采樣頻率為一分鍾。

 

>>> index = pd.date_range('1/1/2000', periods=9, freq='T') >>> series = pd.Series(range(9), index=index) >>> series 2000-01-01 00:00:00 0 2000-01-01 00:01:00 1 2000-01-01 00:02:00 2 2000-01-01 00:03:00 3 2000-01-01 00:04:00 4 2000-01-01 00:05:00 5 2000-01-01 00:06:00 6 2000-01-01 00:07:00 7 2000-01-01 00:08:00 8 Freq: T, dtype: int64
降低采樣頻率為三分鍾

 

>>> series.resample('3T').sum() 2000-01-01 00:00:00 3 2000-01-01 00:03:00 12 2000-01-01 00:06:00 21 Freq: 3T, dtype: int64
降低采樣頻率為三分鍾,但是每個標簽使用right來代替left。請注意,bucket中值的用作標簽。

 

>>> series.resample('3T', label='right').sum() 2000-01-01 00:03:00 3 2000-01-01 00:06:00 12 2000-01-01 00:09:00 21 Freq: 3T, dtype: int64
降低采樣頻率為三分鍾,但是關閉right區間。

 

>>> series.resample('3T', label='right', closed='right').sum() 2000-01-01 00:00:00 0 2000-01-01 00:03:00 6 2000-01-01 00:06:00 15 2000-01-01 00:09:00 15 Freq: 3T, dtype: int64
增加采樣頻率到30秒

 

>>> series.resample('30S').asfreq()[0:5] #select first 5 rows 2000-01-01 00:00:00 0 2000-01-01 00:00:30 NaN 2000-01-01 00:01:00 1 2000-01-01 00:01:30 NaN 2000-01-01 00:02:00 2 Freq: 30S, dtype: float64
增加采樣頻率到30S,使用pad方法填充nan值。

 

>>> series.resample('30S').pad()[0:5] 2000-01-01 00:00:00 0 2000-01-01 00:00:30 0 2000-01-01 00:01:00 1 2000-01-01 00:01:30 1 2000-01-01 00:02:00 2 Freq: 30S, dtype: int64
增加采樣頻率到30S,使用bfill方法填充nan值。

 

>>> series.resample('30S').bfill()[0:5] 2000-01-01 00:00:00 0 2000-01-01 00:00:30 1 2000-01-01 00:01:00 1 2000-01-01 00:01:30 2 2000-01-01 00:02:00 2 Freq: 30S, dtype: int64
通過apply運行一個自定義函數

 

>>> def custom_resampler(array_like): ... return np.sum(array_like)+5
>>> series.resample('3T').apply(custom_resampler) 2000-01-01 00:00:00 8 2000-01-01 00:03:00 17 2000-01-01 00:06:00 26 Freq: 3T, dtype: int64

 

出處:https://blog.csdn.net/wangshuang1631/article/details/52314944


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM