處理模式

在讀取資料或將 Python 物件轉換為 Arrow 物件時,Arrow 會自動推斷最合適的資料類型。

不過,你可能希望手動告知 Arrow 要使用哪些資料類型,例如,要確保與資料庫和資料倉儲系統的互通性。本章包含用於處理模式的食譜。

設定 Arrow 陣列的資料類型

如果你有現有陣列且想要變更它的資料類型,可以用 cast 函式。

import pyarrow as pa

arr = pa.array([1, 2, 3, 4, 5])
print(arr.type)
int64
arr = arr.cast(pa.int8())
print(arr.type)
int8

你也可以透過在陣列建立時提供類型來建立要求 типов。類型

import pyarrow as pa

arr = pa.array([1, 2, 3, 4, 5], type=pa.int8())
print(arr.type)
int8

設定表格的模式

表格存放多個欄,每個欄都有自己的名稱和類型。這些類型的聯集和名稱定義的內容稱為模式。

Arrow 中的模式可以使用 pyarrow.schema() 定義。

import pyarrow as pa

schema = pa.schema([
    ("col1", pa.int8()),
    ("col2", pa.string()),
    ("col3", pa.float64())
])

模式可以在表格建立時提供。

table = pa.table([
    [1, 2, 3, 4, 5],
    ["a", "b", "c", "d", "e"],
    [1.0, 2.0, 3.0, 4.0, 5.0]
], schema=schema)

print(table)
pyarrow.Table
col1: int8
col2: string
col3: double
----
col1: [[1,2,3,4,5]]
col2: [["a","b","c","d","e"]]
col3: [[1,2,3,4,5]]

與陣列一樣,表格可以轉換為不同的模式,只要這些模式是相容即可

schema_int32 = pa.schema([
    ("col1", pa.int32()),
    ("col2", pa.string()),
    ("col3", pa.float64())
])

table = table.cast(schema_int32)

print(table)
pyarrow.Table
col1: int32
col2: string
col3: double
----
col1: [[1,2,3,4,5]]
col2: [["a","b","c","d","e"]]
col3: [[1,2,3,4,5]]

合併多個模式

當你有多個獨立的資料群組要合併時,你可能需要統一這些資料群組的模式,才能建立一個適用於所有資料來源的模式超集。

import pyarrow as pa

first_schema = pa.schema([
    ("country", pa.string()),
    ("population", pa.int32())
])

second_schema = pa.schema([
    ("country_code", pa.string()),
    ("language", pa.string())
])

unify_schemas() 可用於將多個模式合併成一個模式

union_schema = pa.unify_schemas([first_schema, second_schema])

print(union_schema)
country: string
population: int32
country_code: string
language: string

如果合併的模式有重複的欄,只要衝突的欄保留同種類型 (country_code),這些模式仍然可以合併。

third_schema = pa.schema([
    ("country_code", pa.string()),
    ("lat", pa.float32()),
    ("long", pa.float32()),
])

union_schema =  pa.unify_schemas([first_schema, second_schema, third_schema])

print(union_schema)
country: string
population: int32
country_code: string
language: string
lat: float
long: float

如果合併的欄在合併的模式中具有不同的類型,則嘗試合併模式會失敗。例如,如果 country_code 是數字,而不是字串,我們將無法統一模式,因為在 second_schema 中,它已被宣告為一個 pa.string()

third_schema = pa.schema([
    ("country_code", pa.int32()),
    ("lat", pa.float32()),
    ("long", pa.float32()),
])

try:
    union_schema =  pa.unify_schemas([first_schema, second_schema, third_schema])
except (pa.ArrowInvalid, pa.ArrowTypeError) as e:
    print(e)
Unable to merge: Field country_code has incompatible types: string vs int32