
在Pandas中,時間序列(Time Series)是一種特殊的數(shù)據(jù)類型,用于處理時間相關(guān)的數(shù)據(jù)。Pandas提供了豐富的功能和方法,方便對時間序列數(shù)據(jù)進(jìn)行處理和分析。下面是一些針對時間序列的常用操作:
方式① 使用to_datetime
創(chuàng)建時間序列:直接傳入列表即可
import pandas as pd
# 將列表轉(zhuǎn)換為時間戳
date_range = pd.to_datetime(['2024-01-01', '2024-01-02', '2024-01-03'])
date_range
DatetimeIndex(['2024-01-01', '2024-01-02', '2024-01-03'], dtype='datetime64[ns]', freq=None)
方式② 使用pd.date_range()
創(chuàng)建一段連續(xù)的時間范圍:使用指定參數(shù)即可
import pandas as pd
date_range = pd.date_range(start='2024-01-01', end='2024-12-31', freq='D')
date_range
DatetimeIndex(['2024-01-01', '2024-01-02', '2024-01-03', '2024-01-04',
'2024-01-05', '2024-01-06', '2024-01-07', '2024-01-08',
'2024-01-09', '2024-01-10',
...
'2024-12-22', '2024-12-23', '2024-12-24', '2024-12-25',
'2024-12-26', '2024-12-27', '2024-12-28', '2024-12-29',
'2024-12-30', '2024-12-31'],
dtype='datetime64[ns]', length=366, freq='D')
其中,start是起始日期,end是結(jié)束日期,freq是頻率,這里設(shè)置為'D'表示每天。
方式③ 使用Timestamp()
函數(shù)創(chuàng)建一個特定的時間戳:使用指定參數(shù)即可
import pandas as pd
timestamp = pd.Timestamp(year=2023, month=1, day=1, hour=12, minute=30, second=45)
timestamp
Timestamp('2023-01-01 12:30:45')
方式④ 使用 datetime 模塊創(chuàng)建時間戳:使用指定參數(shù)即可
import pandas as pd
from datetime import datetime
timestamp = datetime(2023, 1, 1, 12, 30, 45)
print(timestamp)
2023-01-01 12:30:45
計算一下兩個時間數(shù)據(jù)之差
import pandas as pd
# 創(chuàng)建兩個固定時間
start_time = pd.Timestamp('2024-01-01 12:00:00')
end_time = pd.Timestamp('2024-01-02 14:30:00')
# 計算時間差
time_diff = end_time - start_time
time_diff
Timedelta('1 days 02:30:00')
一個固定時間加上pd.Timedelta
類型的時間差
pd.Timestamp('2024-01-02 14:30:00')+pd.Timedelta('1 days 02:30:00')
Timestamp('2024-01-03 17:00:00')
接下來,我們看看日期做索引的情況
將日期作為索引創(chuàng)建時間序列:
import pandas as pd
data = [1, 2, 3, 4, 5]
dates = pd.date_range(start='2024-01-01', periods=5, freq='D')
ts = pd.Series(data, index=dates)
ts
2024-01-01 1
2024-01-02 2
2024-01-03 3
2024-01-04 4
2024-01-05 5
Freq: D, dtype: int64
其中,periods是時間序列的長度,freq是頻率,這里設(shè)置為'D'表示每天。
import pandas as pd
ts['2024-01-01']
1
使用日期范圍進(jìn)行切片:
import pandas as pd
ts['2024-01-01':'2024-01-05']
2024-01-01 1
2024-01-02 2
2024-01-03 3
2024-01-04 4
2024-01-05 5
Freq: D, dtype: int64
也可以使用切片操作對數(shù)據(jù)進(jìn)行訪問
import pandas as pd
ts[1:4]
2024-01-02 2
2024-01-03 3
2024-01-04 4
Freq: D, dtype: int64
時間序列的重采樣: 將時間序列從高頻率轉(zhuǎn)換為低頻率:
import pandas as pd
ts.resample('W').mean()
2024-01-07 3.0
Freq: W-SUN, dtype: float64
其中,'W'表示按周進(jìn)行重采樣,mean()表示計算每周的平均值。
時間序列的滾動計算: 計算滾動平均值:
import pandas as pd
ts.rolling(window=3).mean()
2024-01-01 NaN
2024-01-02 NaN
2024-01-03 2.0
2024-01-04 3.0
2024-01-05 4.0
Freq: D, dtype: float64
其中,window=3表示窗口大小為3,即計算每3個數(shù)據(jù)的平均值。
時間序列的時間偏移: 將時間序列向前或向后移動:
import pandas as pd
ts.shift(1)
2024-01-01 NaN
2024-01-02 1.0
2024-01-03 2.0
2024-01-04 3.0
2024-01-05 4.0
Freq: D, dtype: float64
其中,1表示向后移動1個時間單位。
在 Pandas 中,可以使用 dt 訪問器來訪問時間戳或時間序列中的各個時間部分,例如年、月、日、小時、分鐘、秒等。通過使用 dt 訪問器,你可以方便地提取和操作時間信息。
下面是一些常用的 dt 訪問器的示例:
import pandas as pd
# 創(chuàng)建一個時間序列
timestamps = pd.Series(pd.date_range('2023-01-01', periods=5, freq='D'))
timestamps
0 2023-01-01
1 2023-01-02
2 2023-01-03
3 2023-01-04
4 2023-01-05
dtype: datetime64[ns]
# 提取年份
year = timestamps.dt.year
year
0 2023
1 2023
2 2023
3 2023
4 2023
dtype: int64
# 提取月份
month = timestamps.dt.month
month
0 1
1 1
2 1
3 1
4 1
dtype: int64
# 提取日期
day = timestamps.dt.day
day
0 1
1 2
2 3
3 4
4 5
dtype: int64
# 提取小時
hour = timestamps.dt.hour
hour
0 0
1 0
2 0
3 0
4 0
dtype: int64
# 提取分鐘
minute = timestamps.dt.minute
minute
0 0
1 0
2 0
3 0
4 0
dtype: int64
# 提取秒數(shù)
second = timestamps.dt.second
second
0 0
1 0
2 0
3 0
4 0
dtype: int64
# 獲取季度
quarter = timestamps.dt.quarter
quarter
0 1
1 1
2 1
3 1
4 1
dtype: int64
# 獲取周數(shù)
week = timestamps.dt.isocalendar().week
week
0 52
1 1
2 1
3 1
4 1
Name: week, dtype: UInt32
# 獲取星期幾的名稱
day_name = timestamps.dt.day_name()
day_name
0 Sunday
1 Monday
2 Tuesday
3 Wednesday
4 Thursday
dtype: object
# 獲取該日期是一年中的第幾天
day_of_year = timestamps.dt.dayofyear
day_of_year
0 1
1 2
2 3
3 4
4 5
dtype: int64
# 獲取該日期是一周中的第幾天(星期一為1,星期日為7)
day_of_week = timestamps.dt.dayofweek + 1
day_of_week
0 7
1 1
2 2
3 3
4 4
dtype: int64
# 獲取該日期是一個月中的第幾天
day_of_month = timestamps.dt.day
day_of_month
0 1
1 2
2 3
3 4
4 5
dtype: int64
# 獲取該日期所在月份的最后一天
end_of_month = timestamps.dt.daysinmonth
end_of_month
0 31
1 31
2 31
3 31
4 31
dtype: int64
import pandas as pd
# 創(chuàng)建時間戳序列
ts = pd.Series(pd.to_timedelta(np.arange(10),unit='m'))
ts
0 0 days 00:00:00
1 0 days 00:01:00
2 0 days 00:02:00
3 0 days 00:03:00
4 0 days 00:04:00
5 0 days 00:05:00
6 0 days 00:06:00
7 0 days 00:07:00
8 0 days 00:08:00
9 0 days 00:09:00
dtype: timedelta64[ns]
# 提取時間戳中的秒數(shù)
seconds = ts.dt.seconds
seconds
0 0
1 60
2 120
3 180
4 240
5 300
6 360
7 420
8 480
9 540
dtype: int64
seconds = ts.dt.to_pytimedelta()
seconds
array([datetime.timedelta(0), datetime.timedelta(seconds=60),
datetime.timedelta(seconds=120), datetime.timedelta(seconds=180),
datetime.timedelta(seconds=240), datetime.timedelta(seconds=300),
datetime.timedelta(seconds=360), datetime.timedelta(seconds=420),
datetime.timedelta(seconds=480), datetime.timedelta(seconds=540)],
dtype=object)
以上是Pandas針對時間序列的一些常用操作和示例代碼
數(shù)據(jù)分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
SQL Server 中 CONVERT 函數(shù)的日期轉(zhuǎn)換:從基礎(chǔ)用法到實戰(zhàn)優(yōu)化 在 SQL Server 的數(shù)據(jù)處理中,日期格式轉(zhuǎn)換是高頻需求 —— 無論 ...
2025-09-18MySQL 大表拆分與關(guān)聯(lián)查詢效率:打破 “拆分必慢” 的認(rèn)知誤區(qū) 在 MySQL 數(shù)據(jù)庫管理中,“大表” 始終是性能優(yōu)化繞不開的話題。 ...
2025-09-18CDA 數(shù)據(jù)分析師:表結(jié)構(gòu)數(shù)據(jù) “獲取 - 加工 - 使用” 全流程的賦能者 表結(jié)構(gòu)數(shù)據(jù)(如數(shù)據(jù)庫表、Excel 表、CSV 文件)是企業(yè)數(shù)字 ...
2025-09-18DSGE 模型中的 Et:理性預(yù)期算子的內(nèi)涵、作用與應(yīng)用解析 動態(tài)隨機(jī)一般均衡(Dynamic Stochastic General Equilibrium, DSGE)模 ...
2025-09-17Python 提取 TIF 中地名的完整指南 一、先明確:TIF 中的地名有哪兩種存在形式? 在開始提取前,需先判斷 TIF 文件的類型 —— ...
2025-09-17CDA 數(shù)據(jù)分析師:解鎖表結(jié)構(gòu)數(shù)據(jù)特征價值的專業(yè)核心 表結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 規(guī)范存儲的結(jié)構(gòu)化數(shù)據(jù),如數(shù)據(jù)庫表、Excel 表、 ...
2025-09-17Excel 導(dǎo)入數(shù)據(jù)含缺失值?詳解 dropna 函數(shù)的功能與實戰(zhàn)應(yīng)用 在用 Python(如 pandas 庫)處理 Excel 數(shù)據(jù)時,“缺失值” 是高頻 ...
2025-09-16深入解析卡方檢驗與 t 檢驗:差異、適用場景與實踐應(yīng)用 在數(shù)據(jù)分析與統(tǒng)計學(xué)領(lǐng)域,假設(shè)檢驗是驗證研究假設(shè)、判斷數(shù)據(jù)差異是否 “ ...
2025-09-16CDA 數(shù)據(jù)分析師:掌控表格結(jié)構(gòu)數(shù)據(jù)全功能周期的專業(yè)操盤手 表格結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 存儲的結(jié)構(gòu)化數(shù)據(jù),如 Excel 表、數(shù)據(jù) ...
2025-09-16MySQL 執(zhí)行計劃中 rows 數(shù)量的準(zhǔn)確性解析:原理、影響因素與優(yōu)化 在 MySQL SQL 調(diào)優(yōu)中,EXPLAIN執(zhí)行計劃是核心工具,而其中的row ...
2025-09-15解析 Python 中 Response 對象的 text 與 content:區(qū)別、場景與實踐指南 在 Python 進(jìn)行 HTTP 網(wǎng)絡(luò)請求開發(fā)時(如使用requests ...
2025-09-15CDA 數(shù)據(jù)分析師:激活表格結(jié)構(gòu)數(shù)據(jù)價值的核心操盤手 表格結(jié)構(gòu)數(shù)據(jù)(如 Excel 表格、數(shù)據(jù)庫表)是企業(yè)最基礎(chǔ)、最核心的數(shù)據(jù)形態(tài) ...
2025-09-15Python HTTP 請求工具對比:urllib.request 與 requests 的核心差異與選擇指南 在 Python 處理 HTTP 請求(如接口調(diào)用、數(shù)據(jù)爬取 ...
2025-09-12解決 pd.read_csv 讀取長浮點數(shù)據(jù)的科學(xué)計數(shù)法問題 為幫助 Python 數(shù)據(jù)從業(yè)者解決pd.read_csv讀取長浮點數(shù)據(jù)時的科學(xué)計數(shù)法問題 ...
2025-09-12CDA 數(shù)據(jù)分析師:業(yè)務(wù)數(shù)據(jù)分析步驟的落地者與價值優(yōu)化者 業(yè)務(wù)數(shù)據(jù)分析是企業(yè)解決日常運營問題、提升執(zhí)行效率的核心手段,其價值 ...
2025-09-12用 SQL 驗證業(yè)務(wù)邏輯:從規(guī)則拆解到數(shù)據(jù)把關(guān)的實戰(zhàn)指南 在業(yè)務(wù)系統(tǒng)落地過程中,“業(yè)務(wù)邏輯” 是連接 “需求設(shè)計” 與 “用戶體驗 ...
2025-09-11塔吉特百貨孕婦營銷案例:數(shù)據(jù)驅(qū)動下的精準(zhǔn)零售革命與啟示 在零售行業(yè) “流量紅利見頂” 的當(dāng)下,精準(zhǔn)營銷成為企業(yè)突圍的核心方 ...
2025-09-11CDA 數(shù)據(jù)分析師與戰(zhàn)略 / 業(yè)務(wù)數(shù)據(jù)分析:概念辨析與協(xié)同價值 在數(shù)據(jù)驅(qū)動決策的體系中,“戰(zhàn)略數(shù)據(jù)分析”“業(yè)務(wù)數(shù)據(jù)分析” 是企業(yè) ...
2025-09-11Excel 數(shù)據(jù)聚類分析:從操作實踐到業(yè)務(wù)價值挖掘 在數(shù)據(jù)分析場景中,聚類分析作為 “無監(jiān)督分組” 的核心工具,能從雜亂數(shù)據(jù)中挖 ...
2025-09-10統(tǒng)計模型的核心目的:從數(shù)據(jù)解讀到?jīng)Q策支撐的價值導(dǎo)向 統(tǒng)計模型作為數(shù)據(jù)分析的核心工具,并非簡單的 “公式堆砌”,而是圍繞特定 ...
2025-09-10