在資料科學領域,時間序列資料的處理與分析至關重要。Pandas 提供了完善的工具和函式,簡化了時間序列資料的操作,從而更有效地進行資料分析。理解時區差異、日期計算、資料篩選和頻率轉換等技巧,是進行準確時間序列分析的基礎。
import pandas as pd
# 建立一個時間序列
ser = pd.Series([1, 2, 3], index=pd.date_range('2024-01-01', periods=3, freq='D'))
# 時區設定
ser_tz = ser.tz_localize('Asia/Taipei')
# 日期偏移
ser_offset = ser + pd.DateOffset(days=7)
# 資料選擇
ser_selected = ser['2024-01-02':'2024-01-03']
# 重取樣
ser_resampled = ser.resample('W').sum()
# 缺失值處理
ser_na = pd.Series([1, None, 3], index=pd.date_range('2024-01-01', periods=3, freq='D'))
ser_filled = ser_na.interpolate()
print(ser_tz, ser_offset, ser_selected, ser_resampled, ser_filled, sep='\n\n')
時間序列資料處理與分析
在資料分析中,時間序列資料的處理和分析是一個重要的課題。時間序列資料是指按照時間順序排列的資料,例如股票價格、氣象資料、網站流量等。pandas 提供了豐富的功能來處理和分析時間序列資料。
時區處理
時區處理是時間序列資料分析中的一個重要問題。時區是指地球上某個地區所採用的標準時間。不同的時區有不同的 UTC 偏移量,例如東八區的 UTC 偏移量是 +8 小時。
pandas 提供了 tz 引數來指定時區。例如:
import pandas as pd
ser = pd.Series([
"2024-01-01 00:00:00",
"2024-01-02 00:00:01",
"2024-01-03 00:00:02"
], dtype="datetime64[ns]")
# 指定時區為 UTC
ser_utc = ser.dt.tz_localize('UTC')
print(ser_utc)
# 將時區轉換為 America/New_York
ser_ny = ser_utc.dt.tz_convert('America/New_York')
print(ser_ny)
程式碼解密:
ser.dt.tz_localize('UTC')將時間序列資料的時區指定為 UTC。ser_utc.dt.tz_convert('America/New_York')將 UTC 時區的時間序列資料轉換為 America/New_York 時區。
日期偏移
日期偏移是指對日期進行加減運算。pandas 提供了 DateOffset 類別來進行日期偏移。例如:
from pandas.tseries.offsets import DateOffset
# 建立一個日期
date = pd.to_datetime('2024-01-01')
# 對日期進行偏移
date_offset = date + DateOffset(days=1)
print(date_offset)
程式碼解密:
pd.to_datetime('2024-01-01')將字串轉換為 datetime 物件。date + DateOffset(days=1)對日期進行偏移,偏移量為 1 天。
時間序列資料選擇
時間序列資料選擇是指根據時間條件選擇資料。pandas 提供了多種方法來選擇時間序列資料。例如:
# 建立一個時間序列資料
ser = pd.Series([
"2024-01-01 00:00:00",
"2024-01-02 00:00:01",
"2024-01-03 00:00:02"
], dtype="datetime64[ns]")
# 選擇特定日期的資料
ser_selected = ser[(ser.dt.date >= pd.to_datetime('2024-01-02').date())]
print(ser_selected)
程式碼解密:
ser.dt.date取得時間序列資料的日期部分。ser[(ser.dt.date >= pd.to_datetime('2024-01-02').date())]選擇日期大於或等於 ‘2024-01-02’ 的資料。
重取樣
重取樣是指將時間序列資料從一個頻率轉換為另一個頻率。pandas 提供了 resample 方法來進行重取樣。例如:
# 建立一個時間序列資料
ser = pd.Series([
1, 2, 3
], index=pd.date_range('2024-01-01', periods=3, freq='D'))
# 將日頻率轉換為月頻率
ser_resampled = ser.resample('M').mean()
print(ser_resampled)
程式碼解密:
pd.date_range('2024-01-01', periods=3, freq='D')建立一個日期範圍,頻率為日。ser.resample('M').mean()將日頻率的時間序列資料重取樣為月頻率,並計算平均值。
每週犯罪和交通事故統計
每週犯罪和交通事故統計是指對每週的犯罪和交通事故資料進行統計。pandas 提供了多種方法來進行統計。例如:
# 建立一個時間序列資料
ser = pd.Series([
1, 2, 3
], index=pd.date_range('2024-01-01', periods=3, freq='D'))
# 將日頻率轉換為周頻率,並計算總和
ser_weekly = ser.resample('W').sum()
print(ser_weekly)
程式碼解密:
ser.resample('W').sum()將日頻率的時間序列資料重取樣為周頻率,並計算總和。
年度變化分析
年度變化分析是指對年度的資料進行分析。pandas 提供了多種方法來進行年度變化分析。例如:
# 建立一個時間序列資料
ser = pd.Series([
1, 2, 3
], index=pd.date_range('2024-01-01', periods=3, freq='D'))
# 將日頻率轉換為年頻率,並計算平均值
ser_yearly = ser.resample('Y').mean()
print(ser_yearly)
程式碼解密:
ser.resample('Y').mean()將日頻率的時間序列資料重取樣為年頻率,並計算平均值。
缺失值處理
缺失值處理是指對缺失的資料進行處理。pandas 提供了多種方法來處理缺失值。例如:
# 建立一個時間序列資料
ser = pd.Series([
1, None, 3
], index=pd.date_range('2024-01-01', periods=3, freq='D'))
# 對缺失值進行插值
ser_interpolated = ser.interpolate()
print(ser_interpolated)
程式碼解密:
ser.interpolate()對缺失值進行插值。
本章介紹了 pandas 中時間序列資料的處理和分析方法,包括時區處理、日期偏移、時間序列資料選擇、重取樣、每週犯罪和交通事故統計、年度變化分析和缺失值處理等。這些方法可以幫助我們更好地理解和分析時間序列資料。
時區感知與日期偏移在時間序列資料處理中的應用
在處理時間序列資料時,時區和日期偏移是兩個非常重要的概念。pandas 函式庫提供了豐富的功能來處理這些問題,使得資料分析和處理變得更加準確和方便。
時區感知的重要性
時間序列資料通常與特定的時區相關聯。預設情況下,pandas 中的 datetime 資料型別是時區無知的(timezone-naive),這意味著它們不包含任何時區資訊。這可能會導致在不同時區之間進行資料轉換或比較時出現問題。
將時區無知的 datetime 轉換為時區感知的 datetime
要使 datetime 資料變為時區感知的,可以使用 pd.Series.dt.tz_localize 方法,並指定一個有效的時區識別符號(例如 “America/New_York”)。
import pandas as pd
# 建立一個時區無知的 datetime Series
ser = pd.Series([
"2024-01-01 00:00:00",
"2024-01-02 00:00:01",
"2024-01-03 00:00:02",
], dtype="datetime64[ns]")
# 將 datetime Series 轉換為時區感知的
ny_ser = ser.dt.tz_localize("America/New_York")
print(ny_ser)
時區轉換
一旦 datetime 資料變為時區感知的,就可以使用 pd.Series.dt.tz_convert 方法將其轉換為其他時區。
# 將 ny_ser 轉換為 "America/Los_Angeles" 時區
la_ser = ny_ser.dt.tz_convert("America/Los_Angeles")
print(la_ser)
處理時區丟失的情況
在某些情況下,可能需要丟棄時區資訊以實作與其他系統的互操作性。這可以透過將 None 傳遞給 pd.Series.dt.tz_localize 方法來實作。同時,建議將原始時區儲存為另一個欄位,以便稍後還原。
# 丟棄時區資訊並儲存原始時區
df = la_ser.to_frame().assign(
datetime=la_ser.dt.tz_localize(None),
timezone=str(la_ser.dt.tz),
).drop(columns=[0])
print(df)
日期偏移的使用
在處理日期時,經常需要對其進行偏移,例如增加或減少特定的時間間隔。pd.DateOffset 物件提供了一種靈活的方式來實作這一點。
基本用法
可以使用 pd.DateOffset 對 datetime 資料進行偏移,例如增加一個月。
# 建立一個 datetime Series
ser = pd.Series([
"2024-01-01",
"2024-01-02",
"2024-01-03",
], dtype="datetime64[ns]")
# 對 ser 增加一個月
offset_ser = ser + pd.DateOffset(months=1)
print(offset_ser)
複雜的日期偏移
pd.DateOffset 支援多種引數,可以同時進行多種日期偏移。
# 對 ser 增加一個月、兩天、三小時、四分鐘和五秒
complex_offset_ser = ser + pd.DateOffset(months=1, days=2, hours=3, minutes=4, seconds=5)
print(complex_offset_ser)
使用 pd.offsets 模組
pandas 的 pd.offsets 模組提供了多種類別,可以用於將日期偏移到特定時間點的開始或結束,例如 pd.offsets.MonthEnd。
# 將 ser 偏移到一月的最後一天
month_end_ser = ser + pd.offsets.MonthEnd()
print(month_end_ser)
日期時間資料處理與選擇
在處理時間序列資料時,pandas 提供了豐富的功能來幫助我們進行日期和時間的運算與選擇。本章節將介紹如何使用 pandas 進行日期時間資料的操作。
日期偏移
pandas 中的 pd.offsets 模組提供了多種日期偏移的方法,可以用來對日期進行前後移動。例如:
import pandas as pd
ser = pd.Series(pd.date_range(start="2024-01-29", periods=3))
print(ser + pd.offsets.MonthBegin())
內容解密:
pd.date_range用於生成一個日期範圍。pd.offsets.MonthBegin將日期移動到下個月的第一天。ser + pd.offsets.MonthBegin()對 ser 中的每個日期進行操作。
自定義營業日
pd.offsets.BusinessDay 和 pd.offsets.CustomBusinessDay 可以用來計算營業日。預設情況下,BusinessDay 只計算週一到週五的日期。
ser = pd.Series(pd.date_range(start="2024-01-29", periods=3))
bd_ser = ser + pd.offsets.BusinessDay(n=3)
print(bd_ser)
內容解密:
n=3表示向前移動 3 個營業日。- 使用
CustomBusinessDay可以自定義營業日和假期。
ser + pd.offsets.CustomBusinessDay(n=3, weekmask="Mon Tue Wed Thu")
內容解密:
weekmask用於指定哪些天是營業日。holidays引數可以用來指定假期。
日期時間索引選擇
當使用日期時間資料作為索引時,pandas 提供了便捷的方法來進行資料選擇。
index = pd.date_range(start="2023-12-27", freq="10D", periods=20)
ser = pd.Series(range(20), index=index)
print(ser.loc["2024-01-06":"2024-01-18"])
內容解密:
pd.date_range生成一個日期時間索引。ser.loc[start:end]用於選擇指定日期範圍內的資料。- 可以直接使用字串代表日期,而不需要建立
pd.Timestamp物件。
日期偏移字串
pandas 支援多種日期偏移字串,如 "WOM-3THU" 代表每月的第三個星期四。
pd.date_range(start="2023-12-27", freq="WOM-3THU", periods=5)
內容解密:
"WOM-3THU"表示每月的第三個星期四。- 其他可用的偏移字串包括
"2W"(每兩週)、"SMS"(每月的第一天和第十五天)等。
日期時間處理流程
@startuml
skinparam backgroundColor #FEFEFE
skinparam componentStyle rectangle
title Pandas時間序列資料處理與分析技巧
package "Pandas 資料處理" {
package "資料結構" {
component [Series
一維陣列] as series
component [DataFrame
二維表格] as df
component [Index
索引] as index
}
package "資料操作" {
component [選取 Selection] as select
component [篩選 Filtering] as filter
component [分組 GroupBy] as group
component [合併 Merge/Join] as merge
}
package "資料轉換" {
component [重塑 Reshape] as reshape
component [透視表 Pivot] as pivot
component [聚合 Aggregation] as agg
}
}
series --> df : 組成
index --> df : 索引
df --> select : loc/iloc
df --> filter : 布林索引
df --> group : 分組運算
group --> agg : 聚合函數
df --> merge : 合併資料
df --> reshape : melt/stack
reshape --> pivot : 重新組織
note right of df
核心資料結構
類似 Excel 表格
end note
@enduml
圖表翻譯: 此圖示展示了使用 pandas 處理日期時間資料的基本流程。首先生成日期範圍,然後應用日期偏移,接著選擇特定的日期範圍,最後結束處理。
時間序列資料操作與重取樣技術詳解
在處理時間序列資料時,Pandas 提供了強大的工具來進行資料選擇、操作和重取樣。本文將探討如何使用 Pandas 進行時間序列資料的操作,特別是在日期時間索引(DatetimeIndex)的使用和重取樣(Resampling)技術。
日期時間索引的建立與使用
Pandas 的 pd.date_range 函式可以用來建立一個日期時間索引。例如,建立一個從 2024 年 1 月 1 日開始、頻率為每秒的索引:
index = pd.date_range(start="2024-01-01", periods=10, freq="s")
ser = pd.Series(range(10), index=index, dtype=pd.Int64Dtype())
ser
輸出結果:
2024-01-01 00:00:00 0
2024-01-01 00:00:01 1
2024-01-01 00:00:02 2
2024-01-01 00:00:03 3
2024-01-01 00:00:04 4
2024-01-01 00:00:05 5
2024-01-01 00:00:06 6
2024-01-01 00:00:07 7
2024-01-01 00:00:08 8
2024-01-01 00:00:09 9
Freq: s, dtype: Int64
內容解密:
- 使用
pd.date_range建立一個從指定日期開始的時間序列索引。 start引數指定起始日期,periods指定生成的時間點數量,freq指定時間間隔。- 將生成的索引賦予一個 Pandas Series,Series 的值為從 0 到 9 的整數。
時間序列資料的選擇
使用 loc 方法可以根據日期時間索引進行資料選擇。例如,選擇特定日期範圍內的資料:
ser.loc["2024-02":"2024-03"]
內容解密:
loc方法用於根據標籤選擇資料。- 使用日期字串可以直接選擇對應日期範圍內的資料。
時區感知(Timezone-Aware)的日期時間索引
可以透過 tz 引數為日期時間索引設定時區:
index = pd.date_range(start="2023-12-27", freq="12h", periods=6, tz="US/Eastern")
ser = pd.Series(range(6), index=index)
ser
輸出結果:
2023-12-27 00:00:00-05:00 0
2023-12-27 12:00:00-05:00 1
2023-12-28 00:00:00-05:00 2
2023-12-28 12:00:00-05:00 3
2023-12-29 00:00:00-05:00 4
2023-12-29 12:00:00-05:00 5
Freq: 12h, dtype: int64
內容解密:
tz引數設定了時區為 “US/Eastern”,生成的索引具有時區訊息。- 輸出結果中的
-05:00表示該時區相對於 UTC 的偏移量。
重取樣(Resampling)技術
重取樣是將時間序列資料從一個頻率轉換到另一個頻率的過程。例如,將每秒的資料重取樣為每3秒的資料:
ser.resample("3s").sum()
內容解密:
resample方法將 Series 的索引按照指定的頻率進行分組。sum方法對每個分組內的資料進行求和。
調整重取樣的區間閉合方式和標籤
預設情況下,重取樣產生的區間是左閉右開的,可以透過 closed 和 label 引數進行調整:
ser.resample("3s", closed="right", label="right").sum()
內容解密:
closed="right"表示區間變為左開右閉。label="right"表示使用區間的右端點作為標籤。