p.233

8. Pandas

章節內容

介紹

· 安装

數據幀 DataFrame

匯入和匯出數據

數據幀的過濾和選擇 Filtering & Selection of a DataFrame

缺失數據處理

• 重塑 DataFrame

與資料庫交互

Df.groupby

添加行數據

Df.sort_values

Df.set_index, df.reset_index

更改列順序

Series.unique、series.nunique

pd.read_csv, pd.read_json

時間序列 Time Series

分類數據類型 Categorical Data Type

df.rolling

df.where、df.mask

p.234

介紹

• Pandas 這個名字來源於 Panel Data 和 Python Data Analysis

世界級的開源專案

為數據操作和分析而編寫的庫

DataFrame 中用於整合操作的優勢

採用 Numpy 風格陣列計算的重要部分

與 Numpy、SciPy、Scikit-learn、Matplotlib 等相關聯

安装

在 iPython 或 Jupyter 或终端機 Terminal 上

pip install pandas

檢查版本

import pandas as pd
pd.__version__

▶ 本地執行結果(Python 3.12 / matplotlib 3.11)

'3.1.1'

'1.5.2'

通用術語翻譯

General terminology translation

pandasExcel
DataFrameworksheet
Seriescolumn
Indexrow headings
rowrow
NaNempty cell
p.235

DataFrame

p.235 原掃描圖
p.235 原掃描圖

Series 是一個類似 np.array 的一維物件,包含一系列值和關聯的數據標籤陣列(索引)。

obj = pd.Series([3.4, 2.5, 6.8, 4.9, 5.8])
obj

   3.4
   2.5
   6.8
   4.9
   5.8
dtype: float64

DataFrame 是二維的、大小可變的、可能異構的表格數據。

In [2]: df = pd.DataFrame( { "Name": ["Alice", "Bobby", "Charlie", "Dorathy" ], "Gender": ["female", "male", "male", "female"], "Age": [25, 30, 58, 42], "Height": [1.68, 1.72, 1.78, 1.63] } ) df

Out[2]:


Name Gender Age Height
Alice female 25 1.68
Bobby male 30 1.72
Charlie male 58 1.78
Dorathy female 42 1.63

⚠️ 本頁有 1 段未能本地執行(#1: SyntaxError: invalid syntax (, line 4)),原因見 OCR_run_report.md

p.236

簡單的 DataFrame(DF)操作

In [3]: df["Name"] Out[3]: 0 Alice 1 Bobby 2 Charlie 3 Dorathy Name: Name, dtype: object

In [4]: df["Height"].max() Out[4]: 1.78

In [5]: df["Age"].mean() Out[5]: 38.75

In [6]: df.describe() Out[6]: Age Height count 4.000000 4.000000 mean 38.750000 1.702500 std 14.682756 0.063443 min 25.000000 1.630000 25% 28.750000 1.667500 50% 36.000000 1.700000 75% 46.000000 1.735000 max 58.000000 1.780000

匯入和匯出數據

p.236 原掃描圖
p.236 原掃描圖

p.237

準備 csv 數據集

yahoo! finance

Search for news, symbols or companies

Q

HANG SENG INDEX (*HSI)

HKSE - HKSE Delayed Price. Currency in HKD

☆ Follow

19,943.51 -66.53 (-0.33%)

At close: February 27 04:09PM HKT

Summary

Chart

Conversations

Historical Data

Options

Components

FAST. PROVEN. GLOBAL.

Delivering ultra-low latency performance across asset classes with global coverage.

DISCOVER REAL-TIME -- ULTRA DIRECT

REFINITIV

An LSEG Business

Time Period: Feb 28, 2022 - Feb 28, 2023

Show: Historical Prices

Frequency: Daily

Apply

Currency in HKD

Download

DateOpenHighLowClose*Adj Close**Volume
Feb 27, 202319,821.0320,086.5319,804.5619,943.5119,943.51-
Feb 24, 202320,223.6720,233.6420,006.7820,010.0420,010.042,061,880,100
Feb 23, 202320,339.1520,601.2220,323.2420,351.3520,351.351,729,748,400
Feb 22, 202320,512.4920,620.9820,344.8620,423.8420,423.841,766,388,300
Feb 21, 202320,859.5020,941.3020,503.0520,529.4920,529.492,004,601,100

將.csv 文件導入 Pandas DataFrame

In [7]: df_hsi = pd.read_csv("^HSI.csv")
df_hsi

Out[7]:

DateOpenHighLowCloseAdj CloseVolume
02022-01-0323510.53906323605.02929723193.18945323274.75000023274.750000734331100
12022-01-0423400.61914123439.30078123146.89062523289.83984423289.8398441760141200
22022-01-0523323.76953123323.76953122851.50000022907.25000022907.2500002768859000
32022-01-0622843.19921923082.94921922709.59960923072.85937523072.8593751765786100
42022-01-0723318.91992223497.50000023162.84960923493.38085923493.3808592602290600
........................
2412022-12-2219537.44921919735.00000019475.67968819679.22070319679.2207031939795100
2422022-12-2319382.23046919686.76953119380.47070319593.06054719593.0605471363741800
2432022-12-2819787.93945320099.76953119787.93945319898.91015619898.9101562823780600
2442022-12-2919648.40039119764.51953119539.83984419741.14062519741.1406252902362900
2452022-12-3020030.84960920073.91992219781.41015619781.41015619781.4101561747706800

246 rows × 7 columns

⚠️ 本頁有 1 段未能本地執行(#1: FileNotFoundError: [Errno 2] No such file or directory: '^HSI.csv'),原因見 OCR_run_report.md

p.238

從 yfinance 導入數據

或者,我們通過 yfinance 包下載數據集。

請注意,yfinance 不是雅虎的附屬公司,而是熱心極客的作品

pip install yfinance

Collecting yfinance

Downloading yfinance-0.2.12-py2.py3-none-any.whl (59 kB) 59.2/59.2 kB 54€

Requirement already satisfied: numpy>=1.16.5 in /Users/honcy] rom yfinance) (1.23.1)

Requirement already satisfied: pandas>=1.3.0 in /Users/honcy] rom yfinance) (1.5.2)

Collecting multitasking>=0.0.7

In [9]: import yfinance as yf

df_HSI = yf.download("^HSI", start="2022-01-01", end="2023-01-01")

[100] 1 of 1 completed

In [10]: df_HSI

Out[10]:

DateOpenHighLowCloseAdj CloseVolume
2022-01-0323510.53906223605.02929723193.18945323274.75000023274.750000734331100
2022-01-0423400.61914123439.30078123146.89062523289.83984423289.8398441760141200
2022-01-0523323.76953123323.76953122851.50000022907.25000022907.2500002768859000
2022-01-0622843.19921923082.94921922709.59960923072.85937523072.8593751765786100
2022-01-0723318.91992223497.50000023162.84960923493.38085923493.3808592602290600
.....................
2022-12-2219537.44921919735.00000019475.67968819679.22070319679.2207031939795100
2022-12-2319382.23046919686.76953119380.47070319593.06054719593.0605471363741800
2022-12-2819787.93945320099.76953119787.93945319898.91015619898.9101562823780600
2022-12-2919648.40039119764.51953119539.83984419741.14062519741.1406252902362900
2022-12-3020030.84960920073.91992219781.41015619781.41015619781.4101561747706800

246 rows × 6 columns

In [11]: print(type(df_hsi))

print(type(df_HSI))

<class 'pandas.core.frame.DataFrame'>

<class 'pandas.core.frame.DataFrame'>

p.239

用於啟動 DataFrame 的更多基本工具

DF.head() DF.tail() DF.shape DF.info() DF.to_datetime() DF.set_index() DF.reset_index() DF.describe() DF.isna() DF.isna().values.any()

您能猜測嗎,為什麼我們需要一個索引嗎?

數據幀的過濾和選擇 Filtering & Selection of a DataFrame

TypeNotes
df[val]Select single column or sequence of columns from the DataFrame; special case conveniences: boolean array (filter rows), slice (slice rows), or boolean DataFrame (set values based on some criterion)
df.loc[val]Selects single row or subset of rows from the DataFrame by label
df.loc[:, val]Selects single column or subset of columns by label
df.loc[val1, val2]Select both rows and columns by label
df.iloc[where]Selects single row or subset of rows from the DataFrame by integer position
df_hsi['關閉'] #選擇為 pd 系列df_hsi[['Close']] #選擇 pd Dfdf_hsi[['Close', 'Volume']] #選擇兩列作為 pd Dfdf_hsi.loc[df_hsi['關閉'] > df_hsi['打開']] #有條件選擇df_hsi.loc[df_hsi.index >= '2022-03-01'] #按索引定位df_hsi.loc[df_hsi.index == '2022-07-04'] #過濾特定日期df_hsi.iloc[0 : 5] #基於整數位置的索引,用於按位置選擇
p.240

數據幀的過濾和選擇 Filtering & Selection of a DataFrame

REMEMBER

Object TypeIndexers
Seriess.loc[indexer]
DataFramedf.loc[row_indexer,column_indexer]

如果只想訪問標量值,最快的方法是使用 .at 和 .iat 方法,這些方法在所有數據結構上都實現。

OpenHighLowCloseAdj CloseVolume
Date
2022-01-0323510.53906323605.02929723193.18945323274.75000023274.750000734331100
2022-01-0423400.61914123439.30078123146.89062523289.83984423289.8398441760141200
2022-01-0523323.76953123323.76953122851.50000022907.25000022907.2500002768859000
2022-01-0622843.19921923082.94921922709.59960923072.85937523072.8593751765786100
2022-01-0723318.91992223497.50000023162.84960923493.38085923493.3808592602290600

In [34]: df_hsi.at[df_hsi.index[4], 'Open']

Out[34]: 23318.919922

In [35]: df_hsi.iat[4, 4]

Out[35]: 23493.380859

p.241

添加新列

在幾乎每一次分析中,我們都需要通過計算創建額外的列,在 Pandas 中,邏輯非常簡單、整潔和快速。感謝矢量化數據管理!

新列中的值的計算是 按元素計算的,您不需要創建迴圈。只需使用 Pandas 內置功能即可。

In [34]: df_hsi["Return"] = df_hsi["Adj Close"].pct_change(1) # percentage change from 1 day before df_hsi

Out[34]:

OpenHighLowCloseAdj CloseVolumeReturn
Date
2022-01-0323510.53906323605.02929723193.18945323274.75000023274.750000734331100NaN
2022-01-0423400.61914123439.30078123146.89062523289.83984423289.83984417601412000.000648
2022-01-0523323.76953123323.76953122851.50000022907.25000022907.2500002768859000-0.016427
2022-01-0622843.19921923082.94921922709.59960923072.85937523072.85937517657861000.007230
2022-01-0723318.91992223497.50000023162.84960923493.38085923493.38085926022906000.018226

In [35]: # add 10,20,50 days moving average for period in [10,20,50]: df_hsi[f"MA(period)"] = df_hsi["Adj Close"].rolling(period).mean() df_hsi.tail(5)

Out[35]:

OpenHighLowCloseAdj CloseVolumeReturnMA10MA20MA50
Date
2022-12-2219537.44921919735.00000019475.67968819679.22070319679.22070319397951000.02707319474.07304719052.52343817540.685566
2022-12-2319382.23046919686.76953119380.47070319593.06054719593.0605471363741800-0.00437819443.29218719153.49746117600.792988
2022-12-2819787.93945320099.76953119787.93945319698.91015619698.91015628237806000.01561019486.82011719283.54599617666.513184
2022-12-2919648.40039119764.51953119539.83984419741.14062519741.1406252902362900-0.00792919501.31425819360.36904317723.044395
2022-12-3020030.84960920073.91992219781.41015619781.41015619781.41015617477088000.00204019512.11035119419.57802717788.447012
p.242

刪除列或行

DataFrame.drop (labels=None, *, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')

In [38]: # Drop columns df_hsi = df_hsi.drop([ 'MA20' ], axis=1) df_hsi

Out[38]: Open High Low Close Adj Close Volume Return MA10 MA50 Date 2022-01-03 23510.539063 23605.029297 23193.189453 23274.750000 23274.750000 734331100 NaN NaN 2022-01-04 23400.619141 23439.300781 23146.890625 23289.839844 23289.839844 1760141200 0.000648 NaN NaN

In [37]: # Drop row df_hsi = df_hsi.drop(index='2022-01-03') df_hsi

Out[37]: Open High Low Close Adj Close Volume Return MA10 MA50 Date 2022-01-04 23400.619141 23439.300781 23146.890625 23289.839844 23289.839844 1760141200 0.000648 NaN NaN 2022-01-05 23323.769531 23323.769531 22851.500000 22907.250000 22907.250000 2768859000 -0.016427 NaN NaN

缺少數據處理

在百萬行的資料庫中,總會有一些不規則的數據,

例如 Null、NaN、None、Empty 或不是定義的 Series 的類型。

根據研究的需要,我們選擇以下其中一種來處理。

沒有硬性規定來處理 NA,做出合理的選擇。

更多觀察工具

注意:如有必要,請將過濾后的數據存儲在新 DF 或原始 DF 中。

p.243

重塑 DF

根據我們擁有的原始資料庫,有時我們需要從列到行進行重塑,反之亦然。

DF.stack ( )

DF.unstack ( )

Stack the columns into single Series

Unstack the rows into columns

In [55]: df_pet = df_pet.stack(level==-1, dropna=True) df_pet

Out[55]: cat weight 1 height 2 dog weight 3 height 4 dtype: int64

Stack the prescribed level(s) from columns to index

In [56]: df_pet = df_pet.unstack() df_pet

Out[56]: weight height cat 1 2 dog 3 4

Pivot a level of the (necessarily hierarchical) index labels.

我們也可以用 stack()建立 3D 數據,但為操作簡便 2D 數據較優勝。

p.244

連接 DF

- 追加行

p.244 原掃描圖
p.244 原掃描圖

- 追加列或系列

p.244 原掃描圖
p.244 原掃描圖

p.245

將 DF 與 KEY 合併

df_merge = pd.merge (df1, df2, how='left', on='键')

In [64]: df1 = pd.DataFrame({'Name': ['Alex', 'Bob', 'Chris'], 'ID': [1, 2, 3]}) df1

Out[64]:

Name ID
Alex 1
Bob 2
Chris 3

In [65]: df2 = pd.DataFrame({'ID': [1,3], 'Score': [65,60]}) df2

Out[65]:

ID Score
0 1 65
1 3 60

In [66]: df = pd.merge(df1, df2, how='left', on='ID') df

Out[66]:

Name ID Score
Alex 1 65.0
Bob 2 NaN
Chris 3 60.0
p.246

繪製 DataFrame-直方分佈圖 Histogram

Pandas 預設圖表庫是 Matplotlib。我們可以用簡單的代碼繪製一個快速圖表。

p.246 原掃描圖
p.246 原掃描圖

我們可以用 Matplotlib 繪製一個更好的圖表

pip install matplotlib

import matplotlib.pyplot as plt fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(15, 10))

ax1.plot(df_hsi.index, df_hsi['Close'], df_hsi['MA10']) ax1.set_ylabel('Share Price') ax1.legend(['Close', 'MA10'])

ax2.bar(df_hsi.index, df_hsi['Volume']) ax2.set_ylabel('Daily volume')

fig.suptitle('Hang Seng Index')

p.246 原掃描圖
p.246 原掃描圖

p.247

與資料庫交互 Interacting with Database

在實際場景中,數據存儲在基於 SQL 的關係資料庫中,例如 SQL Server、PostgreSQL Server 和 MySQL。從基於 SQL 的伺服器載入資料非常簡單。我們以簡單的本地 sqlite3 資料庫為例。

首先,我們創建一個示例表。

In [71]: import sqlite3

In [79]: query = ""
CREATE TABLE sales(
    firstname VARCHAR(20),
    lastname VARCHAR(20),
    age INTEGER,
    sales REAL
);

連接資料庫並執行查詢

In [80]: con = sqlite3.connect('salesdata.sqlite')
con.execute(query)  # you can create a table once
Out[80]: <sqlite3.Cursor at 0x1le70df10>
In [81]: con.commit()
In [82]: data = [('David', 'Chan', 35, 68000.50), ('Edgar', 'Doe', 45, 79000.60), ('Fion', 'Elle', 30, 88650.30)]
stmt = "INSERT INTO sales VALUES(?, ?, ?, ?)"
con.executemany(stmt, data)

▶ 本地執行結果(Python 3.12 / matplotlib 3.11)

<sqlite3.Cursor object at 0x7fde4b466ec0>
Out[82]: <sqlite3.Cursor at 0x11e70db20>
In [83]: con.commit()

⚠️ 本頁有 2 段未能本地執行(#1: SyntaxError: invalid syntax (, line 2); #2: NameError: name 'query' is not defined),原因見 OCR_run_report.md

p.248

拉取數據並導入到 Pandas DF

In [84]: cursor = con.execute('select * from sales')
rows = cursor.fetchall()
rows

Out[84]: [('David', 'Chan', 35, 68000.5),
('Edgar', 'Doe', 45, 79000.6),
('Fion', 'Elle', 30, 88650.3)]

In [85]: cursor.description

Out[85]: (('firstname', None, None, None, None, None, None),
('lastname', None, None, None, None, None, None),
('age', None, None, None, None, None, None),
('sales', None, None, None, None, None, None))

In [88]: df_sales = pd.DataFrame(rows,
                          columns=[x[0] for x in cursor.description])
df_sales

Out[88]:
firstname lastname age sales
David Chan 35 68000.5
Edgar Doe 45 79000.6
Fion Elle 30 88650.3

⚠️ 本頁有 1 段未能本地執行(#1: SyntaxError: invalid syntax (, line 21)),原因見 OCR_run_report.md

p.249

讀寫 HDF5

分層數據格式 Hierarchical Data Format(HDF)是一種檔格式(HDF4、HDF5),旨在存儲和組織大量數據。HDF5 格式旨在解決 HDF4 庫的一些局限性,並滿足現代系統和應用程式的當前和預期要求。

銀行數據可能是其中的一部分,一個檔的大小可能超過10GB。

·寫

df.to_hdf ("data.h5", "df")

從 H5 讀取

pd.read_hdf ("data.h5", "df")

p.250

DF.groupby

除了處理來自不同 DF 的數據外,通常還在同一 DF 中分析類別中的數據。

GroupBy 物件由 groupby 调用返回:df.groupby(),series.groupby()

g = df.groupby ( column ) 表的分組表示形式

可以遍歷組

TeamScore
A8.1
A8.3
A9.2
B6.5
B7.1
B8.6
B7.3
A9.2
B8.6
CompanyModelYearTransmissionEngineSizeMPG
Assume that we have a DF on the right and want to compare Company A and B's top Mile-Per-Gallon.0AA12019Manual1.4 55.4
1AA22020Automatic2.0 67.3
2AA32021Automatic1.4 58.9
3BB12018Manual1.5 52.3
4BB22019Automatic2.0 64.2
1 # groupby columns on Coll and estimate the5BB32020Automatic1.5 68.9
2 # maximum value of column Col2 for each group6BB42021Manual1.5 83.1

Company

A 67.3

B 83.1

Name: MPG, dtype: float64

df.groupby will NOT re-arrange the original sequence of rows. Whereas Pivoting will.

您可以將 'mean'、'max'、'count'、'sum' 等傳遞給 agg()函數。

在指定軸上使用一個或多個操作進行聚合。

<h1 id="h-250-alternatively-you-can-pass-max-to-the-ag">alternatively, you can pass &#x27;max&#x27; to the agg() function</h1>
df.groupby(['Company'])['MPG'].agg('max')
Company
A 67.3
B 83.1
Name: MPG, dtype: float64
1 df.groupby(['Company'])['MPG'].agg(['mean', 'count', 'std'])
mean count std
Company

A 60.533333 3 6.115826
B 67.125000 4 12.736921

📁 Image_20261118_0006.pdf(p.251–300)

⚠️ 本頁有 2 段未能本地執行(#1: NameError: name 'df' is not defined. Did you mean: 'yf'?; #5: NameError: name 'df' is not defined. Did you mean: 'yf'?),原因見 OCR_run_report.md

p.251

添加新的數據行

使用 pd.concat([df, new_df], ignore_index=True) 添加新的數據行。

許多網站使用 df.append(new_df),但很快就會被停用 deprecated。

df = pd.concat([df, pd.DataFrame({
    "Company": ["C"],
    "Model": ["C1"],
    "Year": [2023],
    "Transmission": ["Automatic"],
    "EngineSize": [1.8],
    "MPG": [70],
    })
], ignore_index=True)
CompanyModelYearTransmissionEngineSizeMPG
0AA12019Manual1.455.4
1AA22020Automatic2.067.3
2AA32021Automatic1.458.9
3BB12018Manual1.552.3
4BB22019Automatic2.064.2
5BB32020Automatic1.568.9
6BB42021Manual1.583.1
7CC12023Automatic1.870.0
df = df.append(pd.DataFrame({
"Company": ["C"],
"Model": ["C1"],
"Year": [2023],
"Transmission": ["Automatic"],
"EngineSize": [1.8],
"MPG": [70],
}))
/var/folders/cq/_ztw83fdf0vsg5vkyf8hn0zd40000gn/T/ipykernel_52155/842031746.py:1; FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.
df = df.append(pd.DataFrame(

⚠️ 本頁有 1 段未能本地執行(#2: SyntaxError: invalid decimal literal (, line 9)),原因見 OCR_run_report.md

p.252

訪問 Access DF

存取行的最快方法是按其索引。df.loc[]很方便;df.iloc[]速度很快。

lociloc
Label-based (Location)Integer position-based (iLocation)
A ValueA single label\ne.g.) df.loc['x1']A single integer\ne.g.) df.iloc[0]
A List or ArrayA list of labels\ne.g.) df.loc[['x1', 'x2']]A list of integers\ne.g.) df.iloc[[0, 1]]
A Slice ObjectA slice object with labels\n'x1' and 'x2' are included\ne.g.) df.loc['x1':'x2']A slice object with integers\ni is included, j is not included\ne.g.) df.iloc[i:j]
Conditions or Boolean ArrayConditional that returns a boolean Series\ne.g.) df.loc[df['x1'] > 10]\ndf.loc[[True, False, False]]A boolean array\ne.g.) df.iloc[[True, False, False]]
A Callable FunctionA callable function\ne.g.) df.loc[lambda df: df['x1'] > 10]A callable function\ne.g.) df.iloc[lambda x: x.index %2 == 0]

DataFrame index 索引

在 Pandas DataFrame 中,索引定義了數據的訪問速度。將唯一且相同的列標記為索引,或將其保留為預設的增量整數。典型的索引可以是 datetime 或 id。有 4 種方法可以處理 DataFrame 的索引。

DataFrame.set index使用現有列設置 DataFrame索引。DataFrame.reset index與 set_index 相反。DataFrame.reindex更改為新索引或擴展索引。DataFrame.reindex_like更改為與其他 DataFrame 相同的索引。
p.253

本章小結

我們已經學會了所有基本的pandas df工作。是時候研究一些真實的數據和專案了。

你嘗試的越多,你就越成功。不要害怕bugs和錯誤,高級程式師也每天都在經歷它們

。由於 Pandas、NumPy、SciPy 和 Python 正在快速發展,一些在線資訊可能不會更新。官方文件始終值得信賴。

引用

官方網站:

參考教材:

O'REILLY®

Python for Data Analysis

Data Wrangling with pandas, NumPy & Jupyter

Wes McKinney

pandas

p.254

Series.where () 和 Series.mask ()

1 p = pd.Series([1,2,3,4,5])
2 p
0 1
1 2
2 3
3 4
4 5
dtype: int64
<h3 id="h-254-Replace-values-where-the-condition-is-Fa">Replace values where the condition is False</h3>
p.where(p<=3, 'where p<=3 is false')

1
2
3
where p<=3 is false
where p<=3 is false
dtype: object
<h3 id="h-254-Replace-values-where-the-condition-is-Tr">Replace values where the condition is True</h3>
p.mask(p<=3, 'where p<=3 is true')

where p<=3 is true
where p<=3 is true
where p<=3 is true
4
5
dtype: object

⚠️ 本頁有 3 段未能本地執行(#1: SyntaxError: invalid syntax (, line 3); #2: SyntaxError: invalid syntax (, line 4); #3: SyntaxError: invalid syntax (, line 4)),原因見 OCR_run_report.md

p.255

捲動標準差 Rolling Standard Deviation (STD)

使用標準差衡量波動性和風險。讓使用 250 天性病

hsi['250std'] = hsi['Adj Close'].rolling(250).std()
hsi.tail(5)

▶ 本地執行結果(Python 3.12 / matplotlib 3.11)

Open          High  ...      Volume       250std
Date                                    ...                         
2026-11-12  24121.400391  24132.199219  ...  2809900000  1045.851204
2026-11-13  23871.910156  23930.130859  ...  2915600000  1050.453150
2026-11-16  23708.599609  23894.009766  ...  2695100000  1052.537156
2026-11-17  23521.160156  23626.019531  ...  2997300000  1055.882769
2026-11-18  23428.720703  23436.970703  ...           0          NaN

[5 rows x 7 columns]
Adj CloseMA30MA10EMA10Kurt50Skew50250Max250Min250Std
Date
2022-12-2219679.22070319474.07304719474.07304719329.083741-1.232598-0.14597624965.55078114687.0195312365.320875
2022-12-2319593.06054719443.29218719443.29218719377.079524-1.244126-0.20800824965.55078114687.0195312360.480438
2022-12-2819898.91015619486.82011719486.82011719471.957821-1.239929-0.25853224965.55078114687.0195312354.616331
2022-12-2919741.14062519501.31425819501.31425819520.900149-1.247615-0.31031324965.55078114687.0195312348.397469
2022-12-3019781.41015619512.11035219512.11035219568.265605-1.217817-0.37546124965.55078114687.0195312341.891306

滯後1和滯後2週期的自相關 Autocorrelation of lag1 and lag2 period

自相關是指序列與其前 n 項的相關性。通常使用滯後 1 或滯後 2。

分别使用滞後1天和2天找到HSI自相關。

1 df_all['HSI'].autocorr(lag=1) 0.9941400668946364 1 df_all['HSI'].autocorr(lag=2) 0.9885254205676482 1 pd.plotting.autocorrelation_plot(df_all['HSI']) <AxesSubplot: xlabel='Lag', ylabel='Autocorrelation'> 100 0.75 0.50 0.25 0.00 -0.25 -0.50 -0.75 -1.00 100 200 300 400 500 600 700 Lag

對於機器學習方法,分析師可能會使用AR、ARMA和ARIMA

p.256

指數加權移動平均線 Exponentially Weighted Moving Average (EMA)

在新列「EMA10」中準備「調整平倉價」的10天EMA數據

語法:

Series.ewm (com=None, span=None, halflife=None, alpha=None, min_periods=0, adjust=True, ignore_na=False, axis=0, times=None, method='single')

期初調整係數衰減

yt=xt+(1−α)xt−1+(1−α)2xt−2+…+(1−α)tx01+(1−α)+(1−α)2+…+(1−α)t

hsi['EMA10'] = hsi['Adj Close'].ewm(span=10).mean()
hsi.tail(5)

▶ 本地執行結果(Python 3.12 / matplotlib 3.11)

Open          High  ...       250std         EMA10
Date                                    ...                           
2026-11-12  24121.400391  24132.199219  ...  1045.851204  24098.447316
2026-11-13  23871.910156  23930.130859  ...  1050.453150  24014.656824
2026-11-16  23708.599609  23894.009766  ...  1052.537156  23967.235554
2026-11-17  23521.160156  23626.019531  ...  1055.882769  23883.769076
2026-11-18  23428.720703  23436.970703  ...          NaN  23883.769076

[5 rows x 8 columns]
OpenHighLowCloseAdj CloseVolumeMA30MA10EMA10
Date
2022-12-2219537.44921919735.00000019475.67968819679.22070319679.220703193979510019474.07304719474.07304719329.083741
2022-12-2319382.23046919686.76953119380.47070319593.06054719593.060547136374180019443.29218719443.29218719377.079524
2022-12-2819787.93945320099.76953119787.93945319898.91015619898.910156282378060019486.82011719486.82011719471.957821
2022-12-2919648.40039119764.51953119539.83984419741.14062519741.140625290236290019501.31425819501.31425819520.900149
2022-12-3020030.84960920073.91992219781.41015619781.41015619781.410156174770680019512.11035219512.11035219568.265605

獲得特定時期 MA/EMA

Use slicing series and get the last row of data

1 hsi['Adj Close'][-10:].rolling(10).mean()[ -1]
19512.1103515625
1 hsi['Adj Close'][-10:].ewm(span=10).mean()[ -1]
19618.33963667069

⚠️ 本頁有 1 段未能本地執行(#2: KeyError: -1),原因見 OCR_run_report.md

p.257

Pandas rolling window

Pandas dataframe.rolling()函數提供了滾動窗口計算的功能。滾動窗口計算的概念主要用於信號處理和時間序列數據。

語法:

數據幀。rolling(window,min_periods=None,center=False,win_type=None,on=None,axis=0,closed=None,step=None,method='single')

通過 yfinance 準備恒生指數的時間序列數據。

從 2020-01-01 到 2023-01-01

import numpy as np
import pandas as pd
import yfinance as yf

hsi = yf.download("^HSI", start="2020-01-01", end="2023-01-01")
hsi.head(3)

[**************************100**********] 1 of 1 completed

Open High Low Close Adj Close Volume
Date
2020-01-02 28249.369141 28543.519531 28245.970703 28543.519531 28543.519531 1262732800
2020-01-03 28828.359375 28883.300781 28428.169922 28451.500000 28451.500000 1797904800
2020-01-06 28326.500000 28367.869141 28054.289062 28226.189453 28226.189453 1793426600

移動平均線 Moving Average (MA) - 滾動平均值 rolling mean

準備新的列“MA10”,這是“調整后收盤價”的移動平均線 10 天平均值

hsi['MA10'] = hsi['Adj Close'].rolling(10).mean()
hsi.tail(5)

▶ 本地執行結果(Python 3.12 / matplotlib 3.11)

Open          High  ...         EMA10          MA10
Date                                    ...                            
2026-11-12  24121.400391  24132.199219  ...  24098.447316  24074.250977
2026-11-13  23871.910156  23930.130859  ...  24014.656824  24108.568945
2026-11-16  23708.599609  23894.009766  ...  23967.235554  24144.620898
2026-11-17  23521.160156  23626.019531  ...  23883.769076  24142.840820
2026-11-18  23428.720703  23436.970703  ...  23883.769076           NaN

[5 rows x 9 columns]
OpenHighLowCloseAdj CloseVolumeMA30MA10
Date
2022-12-2219537.44921919735.00000019475.67968819679.22070319679.220703193979510019474.07304719474.073047
2022-12-2319382.23046919886.76953119380.47070319593.06054719593.060547136374180019443.29218719443.292187
2022-12-2819787.93945320099.76953119787.93945319898.91015619898.910156282378060019486.82011719486.820117
2022-12-2919648.40039119764.51953119539.83984419741.14062519741.140625290236290019501.31425819501.314258
2022-12-3020030.84960920073.91992219781.41015619781.41015619781.410156174770680019512.11035219512.110352

⚠️ 本頁有 1 段未能本地執行(#1: SyntaxError: leading zeros in decimal integer literals are not permitt),原因見 OCR_run_report.md

p.258

np.where

使用 np.where 反覆運算條件語句。嵌套(nested)的 np.where 可以應用。

1 df_exam['Result'] = pd.Series(np.where(df_exam['Score']>70, 'Distinction', np.where(df_exam['Score']>50, 'Pass', 'Fail'))
3 ).astype('category')
1 df_exam.sample(5)
ScoreResult
3151Pass
2450Fail
618Fail
3684Distiction
3959Pass

處理類別數據 category data 比字串變數快得多,因為 Pandas 將其視為單個專案。

1 df_exam.info()

<class 'pandas.core.frame.DataFrame'> RangeIndex: 40 entries, 0 to 39 Data columns (total 2 columns):

Column Non-Null Count Dtype


0 Score 40 non-null int64 1 Result 40 non-null category dtypes: category(1), int64(1) memory usage: 620.0 bytes

⚠️ 本頁有 1 段未能本地執行(#1: NameError: name 'df_exam' is not defined),原因見 OCR_run_report.md

p.259

Categorical Data Type 分類數據類型

Pandas 支援分類數據類型,類似於 R 語言。

分類是對應於統計中的分類變數的 pandas 數據類型。分類變數 具有有限且通常固定的可能值(類別;R 中的級別)的數量。例如性別、社會階層、血型、國家隸屬關係、觀察時間或李克特量表的評級。

1 animal = pd.Series(['Bird', "Cat", "Dog", "Elephant"], dtype="category")

1 animal.info()

<class 'pandas.core.series.Series'> RangeIndex: 4 entries, 0 to 3 Series name: None Non-Null Count Dtype


4 non-null category dtypes: category(1) memory usage: 336.0 bytes

有時我們需要在分類數據中對標量數據進行分組。

例如,我們有一個評分表,需要將它們分為幾個類別。

import numpy as np
df_exam = pd.DataFrame({'Score': np.random.randint(1, 101, size=40)})

1 df_exam.head(6)

Score
6
8
41
60
93
35
p.260

對日期時間的列進行分組 Grouping columns for datetime

在某些數據集中,年、月、日列在不同的列中是分開的。您可以將它們分組為pd.to_datetime(df_dt[['年', '月', '日']])

df_dt = pd.DataFrame({'year': [2023, 2023],
    'month': [1, 1],
    'day': [1, 2],
    'sales': [3750, 3900]})

year month day sales
2023 1 1 3750
2023 1 2 3900

df_dt['date'] = pd.to_datetime(df_dt[['year', 'month', 'day']])
df_dt = df_dt.drop(['year', 'month', 'day'], axis=1)
df_dt = df_dt.set_index('date')
df_dt

sales
date
2023-01-01 3750
2023-01-02 3900

Unix epoch time 紀元時間

Unix is enterprise server OS, the time format is a series of number. It can convert to Pandas datetime as well.

pd.to_datetime(1681038343, unit='s') timestamp('2023-04-09 11:05:43') pd.to_datetime(1681038343433502912, unit='ns') timestamp('2023-04-09 11:05:43.433502912')

Unix Epoch Clock

Unix time across midnight into 17 September 2004 (no leap second)
TAI (17 September 2004)UTC (16 to 17 September 2004)Unix time
2004-09-17T00:00:30.752004-09-16T23:59:58.751 095 379 198.75
2004-09-17T00:00:31.002004-09-16T23:59:59.001 095 379 199.00
2004-09-17T00:00:31.252004-09-16T23:59:59.251 095 379 199.25

⚠️ 本頁有 1 段未能本地執行(#1: SyntaxError: leading zeros in decimal integer literals are not permitt),原因見 OCR_run_report.md

p.261

pd.to_datetime

將 series 轉換為 datetime。此函數將標量、類似數位、Series 或 DataFrame/dict 轉換為 pandas datetime 物件。

1 tnx['Date'] = pd.to_datetime(tnx['Date'],format="%Y-%m-%d")
2 tnx.Date
0 2000-01-03
1 2000-01-04
2 2000-01-05
3 2000-01-06
4 2000-01-07
7057 2022-12-26
7058 2022-12-27
7059 2022-12-28
7060 2022-12-29
7061 2022-12-30
Name: Date, Length: 7062, dtype: datetime64[ns]

設置日期時間索引

1 tnx = tnx.set_index('Date')
2 tnx.info()

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 7062 entries, 2000-01-03 to 2022-12-30
Data columns (total 6 columns):
<h3 id="h-261-Column-Non-Null-Count-Dtype">Column Non-Null Count Dtype</h3>
---- ---- ---- ----
0 Open 5780 non-null float64
1 High 5780 non-null float64
2 Low 5780 non-null float64
3 Close 5780 non-null float64
4 Adj Close 5780 non-null float64
5 Volume 5780 non-null float64
dtypes: float64(6)
memory usage: 386.2 KB

1 tnx.tail(3)

DateOpenHighLowCloseAdj CloseVolume
2022-12-283.8183.8903.8153.8873.8870.0
2022-12-293.8683.8863.8183.8353.8350.0
2022-12-303.8693.9053.8313.8793.8790.0
p.262

時間序列 Time Series

時間序列是在連續時間獲得的量的一系列值,它們之間的間隔通常相等。在數學中,時間序列是按時間順序索引(或列出或繪製)的一系列數據點。最常見的是,時間序列是在連續等距的時間點上拍攝的序列。

幾個月的國內銷售物業數據、庫存數據、多年來的天氣數據、即時交通流量數據,都是很好的例子。

要處理時間序列分析,首先要檢查的是索引。它必須設置為日期時間索引。

我們以雅虎財經的 csv 格式的美國財政部數據為例。

Df.index 顯示索引為範圍整數。

Treasury Yield 10 Years (~TNX)

ICE Futures - ICE Futures Real Time Price. Currency in USD

3.2880 +0.0010 (+0.03%)

As of April 6 02:59PM EDT. Market open.

tnx = pd.read_csv("^TNX.csv")
tnx.tail(5)
DateOpenHighLowCloseAdj CloseVolume
70572022-12-26NaNNaNNaNNaNNaNNaN
70582022-12-273.7873.8623.7873.8603.8600.0
70592022-12-283.8183.9903.8153.8873.8870.0
70602022-12-293.8683.8863.8183.8353.8350.0
70612022-12-303.8693.9053.8313.8793.8790.0

1 tnx.index

RangeIndex(start=0, stop=7062, step=1)

df.info()顯示所有系列 dtypes 和資訊

1 tnx.info() <class 'pandas.core.frame.DataFrame'> RangeIndex: 7062 entries, 0 to 7061 Data columns (total 7 columns):

Column Non-Null Count Dtype


⚠️ 本頁有 1 段未能本地執行(#1: FileNotFoundError: [Errno 2] No such file or directory: '^TNX.csv'),原因見 OCR_run_report.md

p.263

Df.to_numpy

df.to_numpy series.to_numpy

將 DataFrame 轉換為 NumPy 陣列。默認情況下,返回陣列的 dtype 將是 DataFrame 中所有類型的通用 NumPy dtype。

data["Case"].to_numpy()

array([ 7325, 7195, 4961, 4881, 6278, 5863, 4941, 5129, 6187, 3649, 4550, 5373, 4130, 4833, 6525, 6559, 5632, 9360, 7811, 6967, 7726, 9449, 11449, 8994, 7380, 7362, 6911, 5716, 7385, 8811, 11281, 8166, 7909, 8260, 8673, 14124, 12463, 10750, 7497, 7298, 7100, 8554, 6308, 4426, 4899, 5369, 7456, 6849, 7812, 7150, 5398, 7032, 9811, 6335,
1 data.to_numpy()
array([[ 7325, 16940],
[ 7195, 16129],
[ 4961, 10272],
[ 4881, 9867],
[ 6278, 12113],
[ 5863, 11658],
[ 4941, 9122],
[ 5129, 11352],
[ 6187, 11997],
[ 3649, 6405],
[ 4550, 11520],

⚠️ 本頁有 3 段未能本地執行(#1: SyntaxError: '[' was never closed (, line 3); #2: NameError: name 'data' is not defined; #3: SyntaxError: '[' was never closed (, line 1)),原因見 OCR_run_report.md

p.264

Df.corr

df.corr(),series.corr()

計算列的成對相關性,不包括 NA/null 值。

data.corr()

Case Amount_mil

Case 1.000000 0.484761
Amount_mil 0.484761 1.000000

data["Case"].corr(data["Amount_mil"])

0.48476064701593535

注意:係數的值始終介於 -1 和 1 之間。

-1 表示完全負線性相關。

+1 表示完全正線性相關。

0 表示變數之間沒有線性依賴關係。

Df.T

DateTimeCaseAmount_mildf.T or df.transpose-DataFrame 的轉置。
2002-6732516940
2002-67195161291data.T
2002-7496110272
2002-848819867DateTime2002-52002-6
2002-9627812113Case73257195
.........Amount.mil1694016129
2018-66713680232 rows × 198 columns
2018-7609165237
2018-8482246765
2018-9350037083
2018-10424338571

198 rows × 2 columns

p.265
<h2 id="h-265-join-Year-and-Month-as-new-column">join Year and Month as new column</h2>
data["DateTime"] = data["Year"].astype(str) + "-" + data["Month"].astype(str)
<h3 id="h-265-drop-Year-and-Month">drop Year and Month</h3>
data = data.drop(['Year', 'Month'], axis=1)
<h3 id="h-265-set-DateTime-as-index">set DateTime as index</h3>
data = data.set_index('DateTime')
data
Case Amount_mil
DateTime• Join Year and Month column as DateTime
2002-5 732516940• Drop Year and Month column
2002-6 719516129• Set index as DateTime
2002-7 496110272
2002-8 48819867
2002-9 627812113

讓我們用 Plotly 繪製一個快速圖表。我們將很快詳細討論 Plotly 的用法。

import plotly.express as px
fig = px.line(data, x=data.index, y=["Case", "Amount_mil"], title='Domestic Sales')
fig.show()

Domestic Sales

p.265 原掃描圖
p.265 原掃描圖

⚠️ 本頁有 2 段未能本地執行(#1: NameError: name 'data' is not defined; #2: NameError: name 'data' is not defined),原因見 OCR_run_report.md

p.266

Pd.read_csv 和 pd.read_json

從 json 讀取文件很簡單,就像 csv 一樣。

JSON(JavaScript Object Notation 物件表示法)是一種羽量級的數據交換格式。人類很容易閱讀和寫作。

API 代表應用程式程式設計介面。意思是,應用程式相互通信的協定。就像我們從 HKO API 中提取的數據一樣,有許多可用的開放數據,並支援 json 格式。

這次我們來導入香港房地產銷售數據。

Domestic Sales (from 2002)

RATING AND VALUATION DEPARTMENT | Housing | XLS | API Available
LAST UPDATED ON: 2023-03-06
UPDATE FREQUENCY: MONTHLY, EXCEPT FOR STOCK, VACANCY AND TAKE-UP TO BE UPDATED ANNUALLY

首先從 data.gov.hk 找到 json 鏈接,然後 pd.read_json

1 link = "https://api.data.gov.hk/v2/filter?q=%7B%2 data = pd.read_json(link)

使用 df.rename(columns={old:new})更改列名

“年”和“月”列應合併為相同的索引。

1 # change the column name
2 data.rename(columns = {'年': 'Year', '月': 'Month', '數目 No.: 'Case',
3 '總值 (百萬元) Consideration ($ million)': 'Amount_mil'), inplace = True)
1 data
YearMonthCaseAmount_mil
020025732516940
120026719516129
220027496110272
32002848819867
420029627812113
...............
19320186671368023
19420187609165237
19520188482246765
19620189350037083
197201810424338571

198 rows x 4 columns

⚠️ 本頁有 2 段未能本地執行(#3: SyntaxError: unterminated string literal (detected at line 1) (<unknow; #4: SyntaxError: unterminated string literal (detected at line 2) (<unknow),原因見 OCR_run_report.md

p.267

series.unique

Series.unique()

返回 Series 物件的唯一值。ndarray 或 ExtensionArray。作為 NumPy 陣列返回的唯一值。

唯一值按出現順序返回。基於 hash table-based 的唯一,因此不排序。Index.unique()提供相同的服務

1 df["EngineSize"].unique()
array([1.4, 2., 1.5, 1.8])

1 df["Company"].unique()
array(['A', 'B', 'C'], dtype=object)

1 df["Year"].unique()
array([2019, 2020, 2021, 2018, 2023])

series.nunique

Series.nunique (dropna=True)

返回物件中唯一元素的數目。

默認情況下排除 NA 值。

dropna=True 表示预设情况下 NaN 不計數。

Index.nunique()提供相同的服務

1 df["EngineSize"].unique()
4
1 df["Year"].unique()
5
1 df["Transmission"].unique()

▶ 本地執行結果(Python 3.12 / matplotlib 3.11)

<StringArray>
[nan, 'Automatic']
Length: 2, dtype: str

⚠️ 本頁有 1 段未能本地執行(#1: NameError: name 'df' is not defined. Did you mean: 'yf'?),原因見 OCR_run_report.md

p.268

更改列/序列顺序 Alter column/series order

更改列順序相對簡單。

1 df[["MPG","EngineSize","Transmission","Company","Model","Year"]]

▶ 本地執行結果(Python 3.12 / matplotlib 3.11)

MPG  EngineSize Transmission Company Model    Year
0      NaN         NaN          NaN     NaN   NaN     NaN
1      NaN         NaN          NaN     NaN   NaN     NaN
2      NaN         NaN          NaN     NaN   NaN     NaN
3      NaN         NaN          NaN     NaN   NaN     NaN
4      NaN         NaN          NaN     NaN   NaN     NaN
...    ...         ...          ...     ...   ...     ...
2848   NaN         NaN          NaN     NaN   NaN     NaN
2849   NaN         NaN          NaN     NaN   NaN     NaN
2850   NaN         NaN          NaN     NaN   NaN     NaN
2851   NaN         NaN     
…(已截斷)
MPGEngineSizeTransmissionCompanyModelYear
055.41.4ManualAA12019
167.32.0AutomaticAA22020
258.91.4AutomaticAA32021
352.31.5ManualBB12018
464.22.0AutomaticBB22019
568.91.5AutomaticBB32020
683.11.5ManualBB42021
770.01.8AutomaticCC12023
870.01.8AutomaticCC12023

使用 .iloc[] 是最快的方法

1df.iloc[:, [5,4,3,0,1,2]]
MPGEngineSizeTransmissionCompanyModelYear
055.41.4ManualAA12019
167.32.0AutomaticAA22020
258.91.4AutomaticAA32021
352.31.5ManualBB12018
464.22.0AutomaticBB22019
568.91.5AutomaticBB32020
683.11.5ManualBB42021
770.01.8AutomaticCC12023
870.01.8AutomaticCC12023
p.269

Df.sort_values - 按行順序排序 sorting rows order

1 df.sort_values(by="Year", ascending=True)

CompanyModelYearTransmissionEngineSizeMPG
3BB12018Manual1.552.3
0AA12019Manual1.455.4
4BB22019Automatic2.064.2
1AA22020Automatic2.067.3
5BB32020Automatic1.568.9
2AA32021Automatic1.458.9
6BB42021Manual1.583.1
7CC12023Automatic1.870.0

按多個系列對行進行排序 Sorting rows by multiple series

df1 = df.sort_values(by=['Company', "Year"], ascending=[True, False])
df1

▶ 本地執行結果(Python 3.12 / matplotlib 3.11)

Date     GoldSpot      zijin  ... Transmission  EngineSize   MPG
2852         NaN          NaN        NaN  ...    Automatic         1.8  70.0
0     2015-01-02  1186.000000   2.210000  ...          NaN         NaN   NaN
1     2015-01-05  1203.900024   2.290000  ...          NaN         NaN   NaN
2     2015-01-06  1219.300049   2.310000  ...          NaN         NaN   NaN
3     2015-01-07  1210.599976   2.360000  ...          NaN         NaN   NaN
...          ...          ...        ...  ...          ...         ...   ...
2847  2026-11-11  4000.500000  28.940001  ...          NaN         NaN   
…(已截斷)
CompanyModelYearTransmissionEngineSizeMPG
2AA32021Automatic1.458.9
1AA22020Automatic2.067.3
0AA12019Manual1.455.4
6BB42021Manual1.583.1
5BB32020Automatic1.568.9
4BB22019Automatic2.064.2
3BB12018Manual1.552.3
7CC12023Automatic1.870.0
p.270

DF.set_index

CompanyModelYearTransmissionEngineSizeMPG
0AA12019Manual1.455.4
1AA22020Automatic2.067.3
2AA32021Automatic1.458.9
3BB12018Manual1.552.3
4BB22019Automatic2.064.2
5BB32020Automatic1.568.9
6BB42021Manual1.583.1
7CC12023Automatic1.870.0

將「Model」設置為新索引

1 df.set_index('Model')

CompanyYearTransmissionEngineSizeMPG
Model
A1A2019Manual1.455.4
A2A2020Automatic2.067.3
A3A2021Automatic1.458.9
B1B2018Manual1.552.3
B2B2019Automatic2.064.2
B3B2020Automatic1.568.9
B4B2021Manual1.583.1
C1C2023Automatic1.870.0
← 第 7 章 NumPy 套件課程總覽第 9 章 數據可視化工具介紹與比較 →