Python系列 - Pandas -時(shí)間頻率pandas.DataFrame.resample

官方網(wǎng)址:https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.resample.html

目的

該篇文章主要以resample的作用、參數(shù)配置解釋,以及它能搭配什么參數(shù)進(jìn)行使用的編寫。

會(huì)按照以下進(jìn)行講解

1、resample能實(shí)現(xiàn)什么效果

2、resample有哪些參數(shù)

3、常用的resample分類實(shí)例

1、resample能實(shí)現(xiàn)什么效果

resample能搭配各種不同時(shí)間維度,進(jìn)行分組聚合。針對(duì)分組情況你可以搭配使用max、minsum、mean等使用。

它可以搭配三種場(chǎng)景使用

groupby

Group by mapping, function, label, or list of labels.

Series.resample

Resample a Series.

DataFrame.resample

Resample a DataFrame

實(shí)例

假設(shè)我有一批數(shù)據(jù),有2行,一行時(shí)間序列,一行具體數(shù)字,以DataFrame展示。具體如下。

import pandas as pd
rng = pd.date_range("1/1/2012", periods=100, freq="D")
ts = pd.Series(np.random.randint(0, 500, len(rng)), index=rng)
ts = ts.reset_index(name='num')
在這里插入圖片描述

注:生成的是2012-01-01 至 2012-04-09年的數(shù)據(jù)。

需求

現(xiàn)在有一個(gè)需求,想要求不同時(shí)間維度下的數(shù)據(jù)之和,例如每周、每月。

完成需求

首先要將日期型字段設(shè)為索引,這一步是為了搭配resample使用,它只能配合datetimeindex

ts = ts.set_index('index')
ts.head()
-----------------------
            num
index          
2012-01-01  104
2012-01-02  249
2012-01-03  177
2012-01-04  262
2012-01-05  318
-------------------------
ts.index
-------------------------
DatetimeIndex(['2012-01-01', '2012-01-02', '2012-01-03', '2012-01-04',
               '2012-01-05', '2012-01-06', '2012-01-07', '2012-01-08',
               '2012-01-09', '2012-01-10', '2012-01-11', '2012-01-12',
               '2012-01-13', '2012-01-14', '2012-01-15', '2012-01-16',
               '2012-01-17', '2012-01-18', '2012-01-19', '2012-01-20',
               '2012-01-21', '2012-01-22', '2012-01-23', '2012-01-24',
               '2012-01-25', '2012-01-26', '2012-01-27', '2012-01-28',
               '2012-01-29', '2012-01-30', '2012-01-31', '2012-02-01',
               '2012-02-02', '2012-02-03', '2012-02-04', '2012-02-05',
               '2012-02-06', '2012-02-07', '2012-02-08', '2012-02-09',
               '2012-02-10', '2012-02-11', '2012-02-12', '2012-02-13',
               '2012-02-14', '2012-02-15', '2012-02-16', '2012-02-17',
               '2012-02-18', '2012-02-19', '2012-02-20', '2012-02-21',
               '2012-02-22', '2012-02-23', '2012-02-24', '2012-02-25',
               '2012-02-26', '2012-02-27', '2012-02-28', '2012-02-29',
               '2012-03-01', '2012-03-02', '2012-03-03', '2012-03-04',
               '2012-03-05', '2012-03-06', '2012-03-07', '2012-03-08',
               '2012-03-09', '2012-03-10', '2012-03-11', '2012-03-12',
               '2012-03-13', '2012-03-14', '2012-03-15', '2012-03-16',
               '2012-03-17', '2012-03-18', '2012-03-19', '2012-03-20',
               '2012-03-21', '2012-03-22', '2012-03-23', '2012-03-24',
               '2012-03-25', '2012-03-26', '2012-03-27', '2012-03-28',
               '2012-03-29', '2012-03-30', '2012-03-31', '2012-04-01',
               '2012-04-02', '2012-04-03', '2012-04-04', '2012-04-05',
               '2012-04-06', '2012-04-07', '2012-04-08', '2012-04-09'],
              dtype='datetime64[ns]', name='index', freq=None)
  • 每周

    # 按照周進(jìn)行求和
    ts.resample('7D').sum()
    --------------------------
                num
    index           
    2012-01-01  1817
    2012-01-08  2460
    2012-01-15  2070
    2012-01-22  2104
    2012-01-29  1812
    2012-02-05  2008
    2012-02-12  1949
    2012-02-19  2092
    2012-02-26  2527
    2012-03-04  1934
    2012-03-11  1856
    2012-03-18  1546
    2012-03-25  1206
    2012-04-01  1865
    2012-04-08   441
    
  • 每月

    # 按照月進(jìn)行求和
    ts.resample('M').sum()
    --------------------------
                 num
    index           
    2012-01-31  9552
    2012-02-29  8233
    2012-03-31  7596
    2012-04-30  2306
    

2、resample有哪些參數(shù)

2.1 resample函數(shù)本身參數(shù)
Signature:
ts.resample(
    rule,
    axis=0,
    closed: Union[str, NoneType] = None,
    label: Union[str, NoneType] = None,
    convention: str = 'start',
    kind: Union[str, NoneType] = None,
    loffset=None,
    base: int = 0,
    on=None,
    level=None,
)
Docstring:
Resample time-series data.
參數(shù) 說明
freq 表示重采樣頻率,例如‘M'、‘5min',Second(15)
how='mean' 用于產(chǎn)生聚合值的函數(shù)名或數(shù)組函數(shù),例如
‘mean'、‘ohlc'、np.max等,默認(rèn)是‘mean',其他常用的值
有:‘first'、‘last'、‘median'、‘max'、‘min'
axis=0 默認(rèn)是縱軸,橫軸設(shè)置axis=1
fill_method = None 升采樣時(shí)如何插值,比如‘ffill'、‘bfill'等
closed = ’right' 在降采樣時(shí),各時(shí)間段的哪一段是閉合的,‘right'或‘left',默認(rèn)‘right'
label= ‘right' 在降采樣時(shí),如何設(shè)置聚合值的標(biāo)簽,例如,9:30-9:35會(huì)被標(biāo)記成9:30還是9:35,
默認(rèn)9:35
loffset = None 面元標(biāo)簽的時(shí)間校正值,比如‘-1s'或Second(-1)用于將聚合標(biāo)簽調(diào)早1秒
limit=None 在向前或向后填充時(shí),允許填充的最大時(shí)期數(shù)
kind = None 聚合到時(shí)期(‘period')或時(shí)間戳(‘timestamp'),默認(rèn)聚合到時(shí)間序列的索引類型
convention = None 當(dāng)重采樣時(shí)期時(shí),將低頻率轉(zhuǎn)換到高頻率所采用的約定(start或end)。默認(rèn)‘end'

函數(shù)參數(shù)如果需細(xì)致體會(huì),可以自己敲代碼實(shí)際應(yīng)用體會(huì),也可以按shift+tab看函數(shù)描述當(dāng)中的實(shí)例情況,這兒不過多贅述。

2.2 freq重采樣參數(shù)

freq重采樣頻率有非常多的參數(shù),這兒羅列一些網(wǎng)絡(luò)收集到的。

別名 偏移量類型 說明
D Day 每日歷日
B BusinessDay 每日工作日(去節(jié)假日)
H Hour 每小時(shí)
T/min Minute 每分鐘
S Second 每秒鐘
M MonthEnd 每月最后一個(gè)日歷日
BM BusinessMonthEnd 每月最后一個(gè)工作日
Q-JAN、Q-FRB QuarterEnd 對(duì)于以指定月份結(jié)束的年度,
每季度最后一月的最后一個(gè)日歷日
A-JAN、A-FEB YearEnd 每年指定月份的最后一個(gè)日歷日
在這里插入圖片描述

3、常用的resample分類實(shí)例

重點(diǎn)還是觀察官方示例,簡(jiǎn)單羅列以下覺得比較重要的。

每十年的1月1日

.resample('10AS')

顯示為以每十年的12月31日

.resample('10A')

days = pd.date_range('1/1/2000', periods=4, freq='D')
>>> d2 = {'price': [10, 11, 9, 13, 14, 18, 17, 19],
...       'volume': [50, 60, 40, 100, 50, 100, 40, 50]}
>>> df2 = pd.DataFrame(d2,
...                    index=pd.MultiIndex.from_product([days,
...                                                     ['morning',
...                                                      'afternoon']]
...                                                     ))
>>> df2
                      price  volume
2000-01-01 morning       10      50
           afternoon     11      60
2000-01-02 morning        9      40
           afternoon     13     100
2000-01-03 morning       14      50
           afternoon     18     100
2000-01-04 morning       17      40
           afternoon     19      50
>>> df2.resample('D', level=0).sum()
            price  volume
2000-01-01     21     110
2000-01-02     22     140
2000-01-03     32     150
2000-01-04     36      90
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容