pyarrow.Table#
- class pyarrow.Table#
基類:
_Tabular一系列頂層命名、等長的 Arrow 陣列集合。
警告
請勿直接呼叫此類的建構函式,請改用
from_*方法之一。示例
>>> import pyarrow as pa >>> n_legs = pa.array([2, 4, 5, 100]) >>> animals = pa.array(["Flamingo", "Horse", "Brittle stars", "Centipede"]) >>> names = ["n_legs", "animals"]
從陣列構造 Table
>>> pa.Table.from_arrays([n_legs, animals], names=names) pyarrow.Table n_legs: int64 animals: string ---- n_legs: [[2,4,5,100]] animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
從 RecordBatch 構造 Table
>>> batch = pa.record_batch([n_legs, animals], names=names) >>> pa.Table.from_batches([batch]) pyarrow.Table n_legs: int64 animals: string ---- n_legs: [[2,4,5,100]] animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
從 pandas DataFrame 構造 Table
>>> import pandas as pd >>> df = pd.DataFrame({'year': [2020, 2022, 2019, 2021], ... 'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]}) >>> pa.Table.from_pandas(df) pyarrow.Table year: int64 n_legs: int64 animals: large_string ---- year: [[2020,2022,2019,2021]] n_legs: [[2,4,5,100]] animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
從陣列字典構造 Table
>>> pydict = {'n_legs': n_legs, 'animals': animals} >>> pa.Table.from_pydict(pydict) pyarrow.Table n_legs: int64 animals: string ---- n_legs: [[2,4,5,100]] animals: [["Flamingo","Horse","Brittle stars","Centipede"]] >>> pa.Table.from_pydict(pydict).schema n_legs: int64 animals: string
從帶元資料的陣列字典構造 Table
>>> my_metadata={"n_legs": "Number of legs per animal"} >>> pa.Table.from_pydict(pydict, metadata=my_metadata).schema n_legs: int64 animals: string -- schema metadata -- n_legs: 'Number of legs per animal'
從行列表構造 Table
>>> pylist = [{'n_legs': 2, 'animals': 'Flamingo'}, {'year': 2021, 'animals': 'Centipede'}] >>> pa.Table.from_pylist(pylist) pyarrow.Table n_legs: int64 animals: string ---- n_legs: [[2,null]] animals: [["Flamingo","Centipede"]]
從帶 pyarrow schema 的行列表構造 Table
>>> my_schema = pa.schema([ ... pa.field('year', pa.int64()), ... pa.field('n_legs', pa.int64()), ... pa.field('animals', pa.string())], ... metadata={"year": "Year of entry"}) >>> pa.Table.from_pylist(pylist, schema=my_schema).schema year: int64 n_legs: int64 animals: string -- schema metadata -- year: 'Year of entry'
使用
pyarrow.table()構造 Table>>> pa.table([n_legs, animals], names=names) pyarrow.Table n_legs: int64 animals: string ---- n_legs: [[2,4,5,100]] animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
- __init__(*args, **kwargs)#
方法
__init__(*args, **kwargs)add_column(self, int i, field_, column)在指定位置向 Table 新增列。
append_column(self, field_, column)在列末尾追加列。
cast(self, Schema target_schema[, safe, options])將 Table 值轉換(Cast)為另一種 Schema。
column(self, i)從 Table 或 RecordBatch 中選擇單列。
combine_chunks(self, MemoryPool memory_pool=None)透過合併該表擁有的資料塊來建立一個新表。
drop(self, columns)刪除一列或多列並返回一個新表。
drop_columns(self, columns)刪除一列或多列並返回一個新的 Table 或 RecordBatch。
drop_null(self)從 Table 或 RecordBatch 中刪除包含缺失值的行。
equals(self, Table other, ...)檢查兩個表的內容是否相等。
field(self, i)透過列名或數字索引選擇 Schema 欄位。
filter(self, mask[, null_selection_behavior])基於布林掩碼從表或記錄批次中選擇行。
flatten(self, MemoryPool memory_pool=None)平鋪(Flatten)此 Table。
from_arrays(arrays[, names, schema, metadata])從 Arrow 陣列構造 Table。
from_batches(batches, Schema schema=None)從 Arrow RecordBatch 序列或迭代器構造 Table。
from_pandas(cls, df, Schema schema=None[, ...])將 pandas.DataFrame 轉換為 Arrow Table。
from_pydict(cls, mapping[, schema, metadata])從 Arrow 陣列或列構造 Table 或 RecordBatch。
from_pylist(cls, mapping[, schema, metadata])從行列表 / 字典構造 Table 或 RecordBatch。
from_struct_array(struct_array)從 StructArray 構造 Table。
get_total_buffer_size(self)表中每個緩衝區所引用的位元組總數。
group_by(self, keys[, use_threads])宣告對錶列的分組。
itercolumns(self)按數字順序迭代所有列。
join(self, right_table, keys[, right_keys, ...])在此表與另一個表之間執行 Join。
join_asof(self, right_table, on, by, tolerance)在此表與另一個表之間執行 asof Join。
remove_column(self, int i)建立刪除指定列後的新 Table。
rename_columns(self, names)建立列名已重新命名為所提供名稱的新表。
replace_schema_metadata(self[, metadata])透過用指定的元資料(可以是 None)替換 Schema 鍵值元資料來建立表的淺複製,這將刪除任何現有的元資料。
select(self, columns)選擇 Table 的列。
set_column(self, int i, field_, column)替換 Table 中指定位置的列。
slice(self[, offset, length])計算此 Table 的零複製切片。
sort_by(self, sorting, **kwargs)按一列或多列對 Table 或 RecordBatch 進行排序。
take(self, indices)從 Table 或 RecordBatch 中選擇行。
to_batches(self[, max_chunksize])將 Table 轉換為 RecordBatch 物件列表。
to_pandas(self[, memory_pool, categories, ...])根據需要轉換為 pandas 相容的 NumPy 陣列或 DataFrame
to_pydict(self, *[, maps_as_pydicts])將 Table 或 RecordBatch 轉換為 dict 或 OrderedDict。
to_pylist(self, *[, maps_as_pydicts])將 Table 或 RecordBatch 轉換為行 / 字典列表。
to_reader(self[, max_chunksize])將 Table 轉換為 RecordBatchReader。
to_string(self, *[, show_metadata, preview_cols])返回 Table 或 RecordBatch 的人類可讀字串表示。
to_struct_array(self[, max_chunksize])轉換為結構型別的分塊陣列。
unify_dictionaries(self, ...)統一所有資料塊中的字典。
validate(self, *[, full])執行驗證檢查。
屬性
Table 或 RecordBatch 的列名。
按數字順序排列的所有列的列表。
所有 ChunkedArray 是否都可由 CPU 訪問。
表元素消耗的總位元組數。
此表中的列數。
此表中的行數。
表及其列的 Schema。
表或記錄批次的維度:(行數,列數)。
- __dataframe__(self, bool nan_as_null: bool = False, bool allow_copy: bool = True)#
返回實現交換協議的資料幀(DataFrame)交換物件。
- 引數:
- 返回:
DataFrameinterchange物件消費庫可以用來接入資料幀的物件。
備註
關於交換協議的詳細資訊:https://data-apis.org/dataframe-protocol/latest/index.html nan_as_null 目前無效;一旦添加了對可為空擴充套件資料型別的支援,該值應傳播到列中。
- add_column(self, int i, field_, column)#
在指定位置向 Table 新增列。
返回添加了列的新表,原始表物件保持不變。
- 引數:
- 返回:
表添加了傳入列的新表。
示例
>>> import pyarrow as pa >>> table = pa.table({'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
新增列
>>> year = [2021, 2022, 2019, 2021] >>> table.add_column(0,"year", [year]) pyarrow.Table year: int64 n_legs: int64 animals: string ---- year: [[2021,2022,2019,2021]] n_legs: [[2,4,5,100]] animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
原始表保持不變
>>> table pyarrow.Table n_legs: int64 animals: string ---- n_legs: [[2,4,5,100]] animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
- append_column(self, field_, column)#
在列末尾追加列。
- 引數:
- 返回:
Table或RecordBatch添加了傳入列的新表或記錄批次。
示例
>>> import pyarrow as pa >>> table = pa.table({'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
在末尾追加列
>>> year = [2021, 2022, 2019, 2021] >>> table.append_column('year', [year]) pyarrow.Table n_legs: int64 animals: string year: int64 ---- n_legs: [[2,4,5,100]] animals: [["Flamingo","Horse","Brittle stars","Centipede"]] year: [[2021,2022,2019,2021]]
- cast(self, Schema target_schema, safe=None, options=None)#
將 Table 值轉換(Cast)為另一種 Schema。
- 引數:
- 返回:
示例
>>> import pyarrow as pa >>> table = pa.table({'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]}) >>> table.schema n_legs: int64 animals: string
定義新 Schema 並轉換表值
>>> my_schema = pa.schema([ ... pa.field('n_legs', pa.duration('s')), ... pa.field('animals', pa.string())] ... ) >>> table.cast(target_schema=my_schema) pyarrow.Table n_legs: duration[s] animals: string ---- n_legs: [[2,4,5,100]] animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
- column(self, i)#
從 Table 或 RecordBatch 中選擇單列。
- 引數:
- 返回:
- column
Array(針對RecordBatch)或ChunkedArray(針對Table)
- column
示例
Table (RecordBatch 用法類似)
>>> import pyarrow as pa >>> import pandas as pd >>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]}) >>> table = pa.Table.from_pandas(df)
透過數字索引選擇列
>>> table.column(0) <pyarrow.lib.ChunkedArray object at ...> [ [ 2, 4, 5, 100 ] ]
透過名稱選擇列
>>> table.column("animals") <pyarrow.lib.ChunkedArray object at ...> [ [ "Flamingo", "Horse", "Brittle stars", "Centipede" ] ]
- column_names#
Table 或 RecordBatch 的列名。
示例
Table (RecordBatch 用法類似)
>>> import pyarrow as pa >>> table = pa.table({'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]}) >>> table.column_names ['n_legs', 'animals']
- columns#
按數字順序排列的所有列的列表。
- 返回:
- columns
listofArray(針對RecordBatch)或listofChunkedArray(針對Table)
- columns
示例
Table (RecordBatch 用法類似)
>>> import pyarrow as pa >>> import pandas as pd >>> df = pd.DataFrame({'n_legs': [None, 4, 5, None], ... 'animals': ["Flamingo", "Horse", None, "Centipede"]}) >>> table = pa.Table.from_pandas(df) >>> table.columns [<pyarrow.lib.ChunkedArray object at ...> [ [ null, 4, 5, null ] ], <pyarrow.lib.ChunkedArray object at ...> [ [ "Flamingo", "Horse", null, "Centipede" ] ]]
- combine_chunks(self, MemoryPool memory_pool=None)#
透過合併該表擁有的資料塊來建立一個新表。
每一列 ChunkedArray 中的所有底層資料塊被連線成零或一個數據塊。
為避免緩衝區溢位,二進位制列可能會被合併成多個數據塊。資料塊將具有最大可能的長度。
- 引數:
- memory_pool
MemoryPool, 預設None 用於記憶體分配(如果需要),否則使用預設記憶體池。
- memory_pool
- 返回:
示例
>>> import pyarrow as pa >>> n_legs = pa.chunked_array([[2, 2, 4], [4, 5, 100]]) >>> animals = pa.chunked_array([["Flamingo", "Parrot", "Dog"], ["Horse", "Brittle stars", "Centipede"]]) >>> names = ["n_legs", "animals"] >>> table = pa.table([n_legs, animals], names=names) >>> table pyarrow.Table n_legs: int64 animals: string ---- n_legs: [[2,2,4],[4,5,100]] animals: [["Flamingo","Parrot","Dog"],["Horse","Brittle stars","Centipede"]] >>> table.combine_chunks() pyarrow.Table n_legs: int64 animals: string ---- n_legs: [[2,2,4,4,5,100]] animals: [["Flamingo","Parrot","Dog","Horse","Brittle stars","Centipede"]]
- drop(self, columns)#
刪除一列或多列並返回一個新表。
Table.drop_columns 的別名,保留以實現向後相容。
- drop_columns(self, columns)#
刪除一列或多列並返回一個新的 Table 或 RecordBatch。
示例
Table (RecordBatch 用法類似)
>>> import pyarrow as pa >>> import pandas as pd >>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]}) >>> table = pa.Table.from_pandas(df)
刪除一列
>>> table.drop_columns("animals") pyarrow.Table n_legs: int64 ---- n_legs: [[2,4,5,100]]
刪除一列或多列
>>> table.drop_columns(["n_legs", "animals"]) pyarrow.Table ... ----
- drop_null(self)#
從 Table 或 RecordBatch 中刪除包含缺失值的行。
有關完整用法,請參閱
pyarrow.compute.drop_null()。- 返回:
Table或RecordBatch具有相同 Schema 且不含缺失值的表格物件。
示例
Table (RecordBatch 用法類似)
>>> import pyarrow as pa >>> table = pa.table({'year': [None, 2022, 2019, 2021], ... 'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", None, "Centipede"]}) >>> table.drop_null() pyarrow.Table year: int64 n_legs: int64 animals: string ---- year: [[2022,2021]] n_legs: [[4,100]] animals: [["Horse","Centipede"]]
- equals(self, Table other, bool check_metadata=False)#
檢查兩個表的內容是否相等。
- 引數:
- other
pyarrow.Table 用於比較的表。
- check_metadatabool, 預設值
False 是否同時檢查 Schema 元資料的相等性。
- other
- 返回:
示例
>>> import pyarrow as pa >>> n_legs = pa.array([2, 2, 4, 4, 5, 100]) >>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"]) >>> names=["n_legs", "animals"] >>> table = pa.Table.from_arrays([n_legs, animals], names=names) >>> table_0 = pa.Table.from_arrays([]) >>> table_1 = pa.Table.from_arrays([n_legs, animals], ... names=names, ... metadata={"n_legs": "Number of legs per animal"}) >>> table.equals(table) True >>> table.equals(table_0) False >>> table.equals(table_1) True >>> table.equals(table_1, check_metadata=True) False
- field(self, i)#
透過列名或數字索引選擇 Schema 欄位。
示例
Table (RecordBatch 用法類似)
>>> import pyarrow as pa >>> table = pa.table({'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]}) >>> table.field(0) pyarrow.Field<n_legs: int64> >>> table.field(1) pyarrow.Field<animals: string>
- filter(self, mask, null_selection_behavior='drop')#
基於布林掩碼從表或記錄批次中選擇行。
Table 可以基於掩碼進行過濾,該掩碼將傳遞給
pyarrow.compute.filter()以執行過濾,也可以透過布林Expression進行過濾。- 引數:
- mask
Array或array-like或Expression 用於過濾表的布林掩碼或
Expression。- null_selection_behavior
str, 預設 “drop” 如何處理掩碼中的空值;如果使用
Expression,則此引數無效。
- mask
- 返回:
- filtered
Table或RecordBatch 與原表 Schema 相同、僅包含透過過濾選擇出的行的表格物件。
- filtered
示例
使用 Table(RecordBatch 用法類似)
>>> import pyarrow as pa >>> table = pa.table({'year': [2020, 2022, 2019, 2021], ... 'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
定義表示式並選擇行
>>> import pyarrow.compute as pc >>> expr = pc.field("year") <= 2020 >>> table.filter(expr) pyarrow.Table year: int64 n_legs: int64 animals: string ---- year: [[2020,2019]] n_legs: [[2,5]] animals: [["Flamingo","Brittle stars"]]
定義掩碼並選擇行
>>> mask=[True, True, False, None] >>> table.filter(mask) pyarrow.Table year: int64 n_legs: int64 animals: string ---- year: [[2020,2022]] n_legs: [[2,4]] animals: [["Flamingo","Horse"]] >>> table.filter(mask, null_selection_behavior='emit_null') pyarrow.Table year: int64 n_legs: int64 animals: string ---- year: [[2020,2022,null]] n_legs: [[2,4,null]] animals: [["Flamingo","Horse",null]]
- flatten(self, MemoryPool memory_pool=None)#
平鋪(Flatten)此 Table。
每個結構(struct)型別的列都會被平鋪,每個結構欄位生成一列。其他列保持不變。
- 引數:
- memory_pool
MemoryPool, 預設None 用於記憶體分配(如果需要),否則使用預設記憶體池
- memory_pool
- 返回:
示例
>>> import pyarrow as pa >>> struct = pa.array([{'n_legs': 2, 'animals': 'Parrot'}, ... {'year': 2022, 'n_legs': 4}]) >>> month = pa.array([4, 6]) >>> table = pa.Table.from_arrays([struct,month], ... names = ["a", "month"]) >>> table pyarrow.Table a: struct<n_legs: int64, animals: string, year: int64> child 0, n_legs: int64 child 1, animals: string child 2, year: int64 month: int64 ---- a: [ -- is_valid: all not null -- child 0 type: int64 [2,4] -- child 1 type: string ["Parrot",null] -- child 2 type: int64 [null,2022]] month: [[4,6]]
平鋪帶有結構欄位的列
>>> table.flatten() pyarrow.Table a.n_legs: int64 a.animals: string a.year: int64 month: int64 ---- a.n_legs: [[2,4]] a.animals: [["Parrot",null]] a.year: [[null,2022]] month: [[4,6]]
- static from_arrays(arrays, names=None, schema=None, metadata=None)#
從 Arrow 陣列構造 Table。
- 引數:
- arrays
listofpyarrow.Array或pyarrow.ChunkedArray 組成表的等長陣列。
- names
listofstr, 可選 表列的名稱。如果未傳入,則必須傳入 schema。
- schema
Schema, 預設值None 建立表的 Schema。如果未傳入,則必須傳入名稱。
- metadata
dict或 Mapping, 預設值None Schema 的可選元資料(如果已推斷)。
- arrays
- 返回:
示例
>>> import pyarrow as pa >>> n_legs = pa.array([2, 4, 5, 100]) >>> animals = pa.array(["Flamingo", "Horse", "Brittle stars", "Centipede"]) >>> names = ["n_legs", "animals"]
從陣列構造 Table
>>> pa.Table.from_arrays([n_legs, animals], names=names) pyarrow.Table n_legs: int64 animals: string ---- n_legs: [[2,4,5,100]] animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
從帶元資料的陣列構造 Table
>>> my_metadata={"n_legs": "Number of legs per animal"} >>> pa.Table.from_arrays([n_legs, animals], ... names=names, ... metadata=my_metadata) pyarrow.Table n_legs: int64 animals: string ---- n_legs: [[2,4,5,100]] animals: [["Flamingo","Horse","Brittle stars","Centipede"]] >>> pa.Table.from_arrays([n_legs, animals], ... names=names, ... metadata=my_metadata).schema n_legs: int64 animals: string -- schema metadata -- n_legs: 'Number of legs per animal'
從帶 pyarrow schema 的陣列構造 Table
>>> my_schema = pa.schema([ ... pa.field('n_legs', pa.int64()), ... pa.field('animals', pa.string())], ... metadata={"animals": "Name of the animal species"}) >>> pa.Table.from_arrays([n_legs, animals], ... schema=my_schema) pyarrow.Table n_legs: int64 animals: string ---- n_legs: [[2,4,5,100]] animals: [["Flamingo","Horse","Brittle stars","Centipede"]] >>> pa.Table.from_arrays([n_legs, animals], ... schema=my_schema).schema n_legs: int64 animals: string -- schema metadata -- animals: 'Name of the animal species'
- static from_batches(batches, Schema schema=None)#
從 Arrow RecordBatch 序列或迭代器構造 Table。
- 引數:
- batchessequence 或
RecordBatch的迭代器 要轉換的 RecordBatch 序列,所有 Schema 必須相等。
- schema
Schema, 預設值None 如果未傳入,將從第一個 RecordBatch 推斷。
- batchessequence 或
- 返回:
示例
>>> import pyarrow as pa >>> n_legs = pa.array([2, 4, 5, 100]) >>> animals = pa.array(["Flamingo", "Horse", "Brittle stars", "Centipede"]) >>> names = ["n_legs", "animals"] >>> batch = pa.record_batch([n_legs, animals], names=names) >>> batch.to_pandas() n_legs animals 0 2 Flamingo 1 4 Horse 2 5 Brittle stars 3 100 Centipede
從 RecordBatch 構造 Table
>>> pa.Table.from_batches([batch]) pyarrow.Table n_legs: int64 animals: string ---- n_legs: [[2,4,5,100]] animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
從 RecordBatches 序列構造 Table
>>> pa.Table.from_batches([batch, batch]) pyarrow.Table n_legs: int64 animals: string ---- n_legs: [[2,4,5,100],[2,4,5,100]] animals: [["Flamingo","Horse","Brittle stars","Centipede"],["Flamingo","Horse","Brittle stars","Centipede"]]
- classmethod from_pandas(cls, df, Schema schema=None, preserve_index=None, nthreads=None, columns=None, bool safe=True)#
將 pandas.DataFrame 轉換為 Arrow Table。
生成的 Arrow Table 中的列型別從 DataFrame 中 pandas.Series 的 dtype 推斷得出。對於非 object 型別的 Series,NumPy 的 dtype 會轉換為其對應的 Arrow 型別。對於 object 型別,我們需要透過檢視該 Series 中的 Python 物件來猜測資料型別。
請注意,object dtype 的 Series 攜帶的資訊並不足以始終得到有意義的 Arrow 型別。如果我們無法推斷型別(例如,DataFrame 長度為 0 或 Series 僅包含 None/nan 物件),則型別設定為 null。可以透過構建顯式 Schema 並將其傳遞給此函式來避免這種行為。
- 引數:
- df
pandas.DataFrame - schema
pyarrow.Schema, 可選 Arrow Table 的預期 Schema。如果我們無法自動推斷,可以使用它來指示列的型別。如果傳遞,輸出將具有完全此 Schema。在 Schema 中指定但在 DataFrame 列或其索引中未找到的列將引發錯誤。DataFrame 中未在 Schema 中指定的額外列或索引級別將被忽略。
- preserve_index
bool, 可選 是否將索引儲存為生成的
Table中的附加列。預設值 None 會將索引儲存為列,但 RangeIndex 除外(僅作為元資料儲存)。使用preserve_index=True強制將其儲存為列。- nthreads
int, 預設值None 如果大於 1,則使用指定的執行緒數並行轉換為 Arrow。預設情況下,這遵循
pyarrow.cpu_count()(最多可使用系統 CPU 核心數個執行緒)。- columns
list, 可選 要轉換的列列表。如果為 None,則使用所有列。
- safebool, 預設
True 檢查是否存在溢位或其他不安全的轉換。
- df
- 返回:
示例
>>> import pyarrow as pa >>> import pandas as pd >>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]}) >>> pa.Table.from_pandas(df) pyarrow.Table n_legs: int64 animals: large_string ---- n_legs: [[2,4,5,100]] animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
- classmethod from_pydict(cls, mapping, schema=None, metadata=None)#
從 Arrow 陣列或列構造 Table 或 RecordBatch。
- 引數:
- 返回:
示例
Table (RecordBatch 用法類似)
>>> import pyarrow as pa >>> n_legs = pa.array([2, 4, 5, 100]) >>> animals = pa.array(["Flamingo", "Horse", "Brittle stars", "Centipede"]) >>> pydict = {'n_legs': n_legs, 'animals': animals}
從陣列字典構造 Table
>>> pa.Table.from_pydict(pydict) pyarrow.Table n_legs: int64 animals: string ---- n_legs: [[2,4,5,100]] animals: [["Flamingo","Horse","Brittle stars","Centipede"]] >>> pa.Table.from_pydict(pydict).schema n_legs: int64 animals: string
從帶元資料的陣列字典構造 Table
>>> my_metadata={"n_legs": "Number of legs per animal"} >>> pa.Table.from_pydict(pydict, metadata=my_metadata).schema n_legs: int64 animals: string -- schema metadata -- n_legs: 'Number of legs per animal'
從帶 pyarrow schema 的陣列字典構造 Table
>>> my_schema = pa.schema([ ... pa.field('n_legs', pa.int64()), ... pa.field('animals', pa.string())], ... metadata={"n_legs": "Number of legs per animal"}) >>> pa.Table.from_pydict(pydict, schema=my_schema).schema n_legs: int64 animals: string -- schema metadata -- n_legs: 'Number of legs per animal'
- classmethod from_pylist(cls, mapping, schema=None, metadata=None)#
從行列表 / 字典構造 Table 或 RecordBatch。
- 引數:
- 返回:
示例
Table (RecordBatch 用法類似)
>>> import pyarrow as pa >>> pylist = [{'n_legs': 2, 'animals': 'Flamingo'}, ... {'n_legs': 4, 'animals': 'Dog'}]
從行列表構造 Table
>>> pa.Table.from_pylist(pylist) pyarrow.Table n_legs: int64 animals: string ---- n_legs: [[2,4]] animals: [["Flamingo","Dog"]]
從帶元資料的行列表構造 Table
>>> my_metadata={"n_legs": "Number of legs per animal"} >>> pa.Table.from_pylist(pylist, metadata=my_metadata).schema n_legs: int64 animals: string -- schema metadata -- n_legs: 'Number of legs per animal'
從帶 pyarrow schema 的行列表構造 Table
>>> my_schema = pa.schema([ ... pa.field('n_legs', pa.int64()), ... pa.field('animals', pa.string())], ... metadata={"n_legs": "Number of legs per animal"}) >>> pa.Table.from_pylist(pylist, schema=my_schema).schema n_legs: int64 animals: string -- schema metadata -- n_legs: 'Number of legs per animal'
- static from_struct_array(struct_array)#
從 StructArray 構造 Table。
StructArray 中的每個欄位都將成為生成的
Table中的一列。- 引數:
- struct_array
StructArray或ChunkedArray 用於構造表的陣列。
- struct_array
- 返回:
示例
>>> import pyarrow as pa >>> struct = pa.array([{'n_legs': 2, 'animals': 'Parrot'}, ... {'year': 2022, 'n_legs': 4, 'animals': 'Goat'}]) >>> pa.Table.from_struct_array(struct).to_pandas() n_legs animals year 0 2 Parrot NaN 1 4 Goat 2022.0
- get_total_buffer_size(self)#
表中每個緩衝區所引用的位元組總數。
陣列可能僅引用緩衝區的一部分。在這種情況下,此方法將高估並返回整個緩衝區的位元組大小。
如果一個緩衝區被多次引用,則它只會被計數一次。
示例
>>> import pyarrow as pa >>> table = pa.table({'n_legs': [None, 4, 5, None], ... 'animals': ["Flamingo", "Horse", None, "Centipede"]}) >>> table.get_total_buffer_size() 76
- group_by(self, keys, use_threads=True)#
宣告對錶列的分組。
生成的分組隨後可用於通過後續的
aggregate()方法執行聚合。- 引數:
- 返回:
示例
>>> import pyarrow as pa >>> table = pa.table({'year': [2020, 2022, 2021, 2022, 2019, 2021], ... 'n_legs': [2, 2, 4, 4, 5, 100], ... 'animal': ["Flamingo", "Parrot", "Dog", "Horse", ... "Brittle stars", "Centipede"]}) >>> table.group_by('year').aggregate([('n_legs', 'sum')]) pyarrow.Table year: int64 n_legs_sum: int64 ---- year: [[2020,2022,2021,2019]] n_legs_sum: [[2,6,104,5]]
- is_cpu#
所有 ChunkedArray 是否都可由 CPU 訪問。
- itercolumns(self)#
按數字順序迭代所有列。
- 生成:
Array(針對RecordBatch)或ChunkedArray(針對Table)
示例
Table (RecordBatch 用法類似)
>>> import pyarrow as pa >>> table = pa.table({'n_legs': [None, 4, 5, None], ... 'animals': ["Flamingo", "Horse", None, "Centipede"]}) >>> for i in table.itercolumns(): ... print(i.null_count) ... 2 1
- join(self, right_table, keys, right_keys=None, join_type='left outer', left_suffix=None, right_suffix=None, coalesce_keys=True, use_threads=True, filter_expression=None)#
在此表與另一個表之間執行 Join。
Join 的結果將是一個新 Table,可以在其上應用進一步的操作。
- 引數:
- right_table
Table 要連線到當前表的表,在 Join 操作中充當右側表。
- keys
str或list[str] 當前表中應作為 Join 操作左側鍵的列。
- right_keys
str或list[str], 預設None right_table 中應作為 Join 操作右側鍵的列。如果為
None,則使用與左側表相同的鍵名。- join_type
str, 預設 “left outer” 應執行的 Join 型別,取值包括(“left semi”, “right semi”, “left anti”, “right anti”, “inner”, “left outer”, “right outer”, “full outer”)
- left_suffix
str, 預設None 要新增到左側列名稱的字尾。這可以防止當左右表中的列名稱衝突時產生混淆。
- right_suffix
str, 預設None 要新增到右側列名稱的字尾。這可以防止當左右表中的列名稱衝突時產生混淆。
- coalesce_keysbool, 預設
True 是否應從 Join 結果的一側省略重複的鍵。
- use_threadsbool, 預設
True 是否使用多執行緒。
- filter_expression
pyarrow.compute.Expression 應用於匹配行的剩餘過濾器。
- right_table
- 返回:
示例
>>> import pyarrow as pa >>> import pyarrow.compute as pc >>> t1 = pa.table({'id': [1, 2, 3], ... 'year': [2020, 2022, 2019]}) >>> t2 = pa.table({'id': [3, 4], ... 'n_legs': [5, 100], ... 'animal': ["Brittle stars", "Centipede"]})
左外連線
>>> t1.join(t2, 'id').combine_chunks().sort_by('year') pyarrow.Table id: int64 year: int64 n_legs: int64 animal: string ---- id: [[3,1,2]] year: [[2019,2020,2022]] n_legs: [[5,null,null]] animal: [["Brittle stars",null,null]]
全外連線
>>> t1.join(t2, 'id', join_type="full outer").combine_chunks().sort_by('year') pyarrow.Table id: int64 year: int64 n_legs: int64 animal: string ---- id: [[3,1,2,4]] year: [[2019,2020,2022,null]] n_legs: [[5,null,null,100]] animal: [["Brittle stars",null,null,"Centipede"]]
右外連線
>>> t1.join(t2, 'id', join_type="right outer").combine_chunks().sort_by('year') pyarrow.Table year: int64 id: int64 n_legs: int64 animal: string ---- year: [[2019,null]] id: [[3,4]] n_legs: [[5,100]] animal: [["Brittle stars","Centipede"]]
右反連線
>>> t1.join(t2, 'id', join_type="right anti") pyarrow.Table id: int64 n_legs: int64 animal: string ---- id: [[4]] n_legs: [[100]] animal: [["Centipede"]]
帶有預期不匹配過濾表示式的內連線
>>> t1.join(t2, 'id', join_type="inner", filter_expression=pc.equal(pc.field("n_legs"), 100)) pyarrow.Table id: int64 year: int64 n_legs: int64 animal: string ---- id: [] year: [] n_legs: [] animal: []
- join_asof(self, right_table, on, by, tolerance, right_on=None, right_by=None)#
在此表與另一個表之間執行 asof Join。
這類似於左連線,但我們匹配的是最近的鍵而不是相等的鍵。兩個表都必須按鍵排序。這種型別的 Join 最適用於未完全對齊的時間序列資料。
在用“on”搜尋之前,可選地在“by”上匹配等效鍵。
Join 的結果將是一個新 Table,可以在其上應用進一步的操作。
- 引數:
- right_table
Table 要連線到當前表的表,在 Join 操作中充當右側表。
- on
str 當前表中應用作 Join 操作左側“on”鍵的列。
在“on”鍵上使用非精確匹配,即當且僅當
right.on - left.on位於範圍[min(0, tolerance), max(0, tolerance)]內時,該行才被視為匹配。輸入資料集必須按“on”鍵排序。必須是具有通用型別的單個欄位。
目前,“on”鍵必須是整數、日期或時間戳型別。
- by
str或list[str] 當前表中應用作 Join 操作左側鍵的列。然後僅針對這些列中的匹配項執行 Join 操作。
- tolerance
int 非精確“on”鍵匹配的容差。當
right.on - left.on位於範圍[min(0, tolerance), max(0, tolerance)]內時,右側行被視為與左側行匹配。tolerance可以是負數,在這種情況下發生 past-as-of-join(當且僅當
tolerance <= right.on - left.on <= 0時匹配);正數,在這種情況下發生 future-as-of-join(當且僅當
0 <= right.on - left.on <= tolerance時匹配);或為零,在這種情況下發生 exact-as-of-join(當且僅當
right.on == left.on時匹配)。
容差的單位與“on”鍵相同。
- right_on
str或list[str], 預設None right_table 中應用作 Join 操作右側“on”鍵的列。如果為
None,則使用與左側表相同的鍵名。- right_by
str或list[str], 預設None right_table 中應作為 Join 操作右側鍵的列。如果為
None,則使用與左側表相同的鍵名。
- right_table
- 返回:
示例
>>> import pyarrow as pa >>> t1 = pa.table({'id': [1, 3, 2, 3, 3], ... 'year': [2020, 2021, 2022, 2022, 2023]}) >>> t2 = pa.table({'id': [3, 4], ... 'year': [2020, 2021], ... 'n_legs': [5, 100], ... 'animal': ["Brittle stars", "Centipede"]})
>>> t1.join_asof(t2, on='year', by='id', tolerance=-2) pyarrow.Table id: int64 year: int64 n_legs: int64 animal: string ---- id: [[1,3,2,3,3]] year: [[2020,2021,2022,2022,2023]] n_legs: [[null,5,null,5,null]] animal: [[null,"Brittle stars",null,"Brittle stars",null]]
- nbytes#
表元素消耗的總位元組數。
換句話說,是所有引用的緩衝區範圍中位元組的總和。
與 get_total_buffer_size 不同,此方法會考慮陣列偏移量。
如果多個數組之間共享緩衝區,則共享部分可能會被多次計算。
字典陣列的字典將始終被完整計算,即使陣列僅引用了字典的一部分。
示例
>>> import pyarrow as pa >>> table = pa.table({'n_legs': [None, 4, 5, None], ... 'animals': ["Flamingo", "Horse", None, "Centipede"]}) >>> table.nbytes 72
- num_columns#
此表中的列數。
- 返回:
示例
>>> import pyarrow as pa >>> import pandas as pd >>> df = pd.DataFrame({'n_legs': [None, 4, 5, None], ... 'animals': ["Flamingo", "Horse", None, "Centipede"]}) >>> table = pa.Table.from_pandas(df) >>> table.num_columns 2
- num_rows#
此表中的行數。
根據表的定義,所有列具有相同的行數。
- 返回:
示例
>>> import pyarrow as pa >>> import pandas as pd >>> df = pd.DataFrame({'n_legs': [None, 4, 5, None], ... 'animals': ["Flamingo", "Horse", None, "Centipede"]}) >>> table = pa.Table.from_pandas(df) >>> table.num_rows 4
- remove_column(self, int i)#
建立刪除指定列後的新 Table。
示例
>>> import pyarrow as pa >>> table = pa.table({'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]}) >>> table.remove_column(1) pyarrow.Table n_legs: int64 ---- n_legs: [[2,4,5,100]]
- rename_columns(self, names)#
建立列名已重新命名為所提供名稱的新表。
- 引數:
- 返回:
- 引發:
KeyError如果傳遞的名稱對映中任何列名不存在。
示例
>>> import pyarrow as pa >>> table = pa.table({'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]}) >>> new_names = ["n", "name"] >>> table.rename_columns(new_names) pyarrow.Table n: int64 name: string ---- n: [[2,4,5,100]] name: [["Flamingo","Horse","Brittle stars","Centipede"]] >>> new_names = {"n_legs": "n", "animals": "name"} >>> table.rename_columns(new_names) pyarrow.Table n: int64 name: string ---- n: [[2,4,5,100]] name: [["Flamingo","Horse","Brittle stars","Centipede"]]
- replace_schema_metadata(self, metadata=None)#
透過用指定的元資料(可以是 None)替換 Schema 鍵值元資料來建立表的淺複製,這將刪除任何現有的元資料。
示例
>>> import pyarrow as pa >>> import pandas as pd >>> df = pd.DataFrame({'year': [2020, 2022, 2019, 2021], ... 'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]}) >>> table = pa.Table.from_pandas(df)
用 pyarrow schema 和元資料構造 Table
>>> my_schema = pa.schema([ ... pa.field('n_legs', pa.int64()), ... pa.field('animals', pa.string())], ... metadata={"n_legs": "Number of legs per animal"}) >>> table= pa.table(df, my_schema) >>> table.schema n_legs: int64 animals: string -- schema metadata -- n_legs: 'Number of legs per animal' pandas: ...
建立已刪除 Schema 元資料的 Table 的淺複製
>>> table.replace_schema_metadata().schema n_legs: int64 animals: string
建立具有新 Schema 元資料的 Table 的淺複製
>>> metadata={"animals": "Which animal"} >>> table.replace_schema_metadata(metadata = metadata).schema n_legs: int64 animals: string -- schema metadata -- animals: 'Which animal'
- schema#
表及其列的 Schema。
- 返回:
示例
>>> import pyarrow as pa >>> table = pa.table({'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]}) >>> table.schema n_legs: int64 animals: string
- select(self, columns)#
選擇 Table 的列。
返回帶有指定列且元資料被保留的新 Table。
- 引數:
- columns類列表
要選擇的列名或整數索引。
- 返回:
示例
>>> import pyarrow as pa >>> table = pa.table({'year': [2020, 2022, 2019, 2021], ... 'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]}) >>> table.select([0,1]) pyarrow.Table year: int64 n_legs: int64 ---- year: [[2020,2022,2019,2021]] n_legs: [[2,4,5,100]] >>> table.select(["year"]) pyarrow.Table year: int64 ---- year: [[2020,2022,2019,2021]]
- set_column(self, int i, field_, column)#
替換 Table 中指定位置的列。
- 引數:
- 返回:
表設定了傳入列的新表。
示例
>>> import pyarrow as pa >>> table = pa.table({'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
替換一列
>>> year = [2021, 2022, 2019, 2021] >>> table.set_column(1,'year', [year]) pyarrow.Table n_legs: int64 year: int64 ---- n_legs: [[2,4,5,100]] year: [[2021,2022,2019,2021]]
- shape#
表或記錄批次的維度:(行數,列數)。
示例
>>> import pyarrow as pa >>> table = pa.table({'n_legs': [None, 4, 5, None], ... 'animals': ["Flamingo", "Horse", None, "Centipede"]}) >>> table.shape (4, 2)
- slice(self, offset=0, length=None)#
計算此 Table 的零複製切片。
示例
>>> import pyarrow as pa >>> table = pa.table({'year': [2020, 2022, 2019, 2021], ... 'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]}) >>> table.slice(length=3) pyarrow.Table year: int64 n_legs: int64 animals: string ---- year: [[2020,2022,2019]] n_legs: [[2,4,5]] animals: [["Flamingo","Horse","Brittle stars"]] >>> table.slice(offset=2) pyarrow.Table year: int64 n_legs: int64 animals: string ---- year: [[2019,2021]] n_legs: [[5,100]] animals: [["Brittle stars","Centipede"]] >>> table.slice(offset=2, length=1) pyarrow.Table year: int64 n_legs: int64 animals: string ---- year: [[2019]] n_legs: [[5]] animals: [["Brittle stars"]]
- sort_by(self, sorting, **kwargs)#
按一列或多列對 Table 或 RecordBatch 進行排序。
- 引數:
- 返回:
Table或RecordBatch按排序鍵排序後的新表格物件。
示例
Table (RecordBatch 用法類似)
>>> import pyarrow as pa >>> table = pa.table({'year': [2020, 2022, 2021, 2022, 2019, 2021], ... 'n_legs': [2, 2, 4, 4, 5, 100], ... 'animal': ["Flamingo", "Parrot", "Dog", "Horse", ... "Brittle stars", "Centipede"]}) >>> table.sort_by('animal') pyarrow.Table year: int64 n_legs: int64 animal: string ---- year: [[2019,2021,2021,2020,2022,2022]] n_legs: [[5,100,4,2,4,2]] animal: [["Brittle stars","Centipede","Dog","Flamingo","Horse","Parrot"]]
- take(self, indices)#
從 Table 或 RecordBatch 中選擇行。
完整用法請參見
pyarrow.compute.take()。- 引數:
- indices
Array或array-like 表格物件中將返回其行的索引。
- indices
- 返回:
Table或RecordBatch具有相同 Schema、包含所取行的表格物件。
示例
Table (RecordBatch 用法類似)
>>> import pyarrow as pa >>> table = pa.table({'year': [2020, 2022, 2019, 2021], ... 'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]}) >>> table.take([1,3]) pyarrow.Table year: int64 n_legs: int64 animals: string ---- year: [[2022,2021]] n_legs: [[4,100]] animals: [["Horse","Centipede"]]
- to_batches(self, max_chunksize=None)#
將 Table 轉換為 RecordBatch 物件列表。
請注意,此方法是零複製的,它只是在不同的 API 下公開相同的資料。
- 引數:
- 返回:
示例
>>> import pyarrow as pa >>> import pandas as pd >>> df = pd.DataFrame({'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]}) >>> table = pa.Table.from_pandas(df)
將 Table 轉換為 RecordBatch
>>> table.to_batches()[0].to_pandas() n_legs animals 0 2 Flamingo 1 4 Horse 2 5 Brittle stars 3 100 Centipede
將 Table 轉換為 RecordBatch 列表
>>> table.to_batches(max_chunksize=2)[0].to_pandas() n_legs animals 0 2 Flamingo 1 4 Horse >>> table.to_batches(max_chunksize=2)[1].to_pandas() n_legs animals 0 5 Brittle stars 1 100 Centipede
- to_pandas(self, memory_pool=None, categories=None, bool strings_to_categorical=False, bool zero_copy_only=False, bool integer_object_nulls=False, bool date_as_object=True, bool timestamp_as_object=False, bool use_threads=True, bool deduplicate_objects=True, bool ignore_metadata=False, bool safe=True, bool split_blocks=False, bool self_destruct=False, str maps_as_pydicts=None, types_mapper=None, bool coerce_temporal_nanoseconds=False)#
根據需要轉換為 pandas 相容的 NumPy 陣列或 DataFrame
- 引數:
- memory_pool
MemoryPool, 預設None 用於分配的 Arrow MemoryPool。如果未傳遞,則使用預設記憶體池。
- categories
list, 預設empty 應作為 pandas.Categorical 返回的欄位列表。僅適用於表格類資料結構。
- strings_to_categoricalbool, 預設
False 將字串 (UTF8) 和二進位制型別編碼為 pandas.Categorical。
- zero_copy_onlybool, 預設
False 如果此函式呼叫需要複製底層資料,則引發 ArrowException。
- integer_object_nullsbool, 預設
False 將帶有 null 的整數轉換為物件
- date_as_objectbool, 預設
True 將日期轉換為物件。如果為 False,則轉換為具有等效時間單位的 datetime64 dtype(如果支援)。注意:在 pandas 版本 < 2.0 中,僅支援 datetime64[ns] 轉換。
- timestamp_as_objectbool, 預設
False 將非納秒時間戳 (np.datetime64) 轉換為物件。這在 pandas 1.x 版本中很有用,如果您有不適合納秒時間戳正常日期範圍(公元 1678 年至 2262 年)的時間戳。pandas 2.0 版本支援非納秒時間戳。如果為 False,則所有時間戳都將轉換為 datetime64 dtype。
- use_threadsbool, 預設
True 是否使用多個執行緒並行化轉換。
- deduplicate_objectsbool, 預設
True 建立時不要建立多個 Python 物件副本,以節省記憶體使用。轉換速度會變慢。
- ignore_metadatabool, 預設
False 如果為 True,則在存在時,不使用‘pandas’元資料來重建 DataFrame 索引
- safebool, 預設
True 對於某些資料型別,需要進行轉換才能將資料儲存在 pandas DataFrame 或 Series 中(例如,時間戳在 pandas 中始終以納秒儲存)。此選項控制這是否為安全轉換。
- split_blocksbool, 預設
False 如果為 True,則從 RecordBatch 或 Table 建立 pandas.DataFrame 時,為每一列生成一個內部“塊”。雖然這可以暫時減少記憶體,但請注意,各種 pandas 操作可能會觸發“合併”,這可能會導致記憶體使用量激增。
- self_destructbool, 預設
False 實驗性:如果為 True,則嘗試在將 Arrow 物件轉換為 pandas 時釋放原始 Arrow 記憶體。如果您在使用此選項呼叫 to_pandas 後使用該物件,程式將會崩潰。
請注意,您可能不會總是看到記憶體使用量的改善。例如,如果多個列共享底層分配,則在轉換所有列之前,無法釋放記憶體。
- maps_as_pydicts
str, 可選, 預設 None 有效值為 None、‘lossy’ 或 ‘strict’。預設行為 (None) 是將 Arrow Map 陣列轉換為與 Arrow Map 順序相同的原生 Python 關聯列表(元組列表),如 [(key1, value1), (key2, value2), …]。
如果為 ‘lossy’ 或 ‘strict’,則將 Arrow Map 陣列轉換為原生 Python 字典。這可能會更改 (key, value) 對的排序,並會去除多個鍵的重複項,從而導致可能的資料丟失。
如果為 ‘lossy’,則此鍵去重會導致檢測到時列印警告。如果為 ‘strict’,則會在檢測到時引發異常。
- types_mapper函式, 預設
None 將 pyarrow DataType 對映到 pandas ExtensionDtype 的函式。這可用於覆蓋內建 pyarrow 型別轉換的預設 pandas 型別,或在 Table Schema 中缺少 pandas_metadata 時使用。該函式接收一個 pyarrow DataType,並預期返回一個 pandas ExtensionDtype,如果應使用預設轉換,則返回
None。如果您有一個字典對映,可以將dict.get作為函式傳遞。- coerce_temporal_nanosecondsbool, 預設
False 僅適用於 pandas 版本 >= 2.0。這是一個遺留選項,用於在轉換為 pandas 時將 date32、date64、duration 和 timestamp 時間單位強制轉換為納秒。這是 pandas 1.x 版本中的預設行為。如果您想在 pandas 版本 >= 2.0 中使用此強制轉換以保持向後相容性(否則不建議這樣做),請將此選項設定為 True。
- memory_pool
- 返回:
pandas.Series或pandas.DataFrame,具體取決於物件type
示例
>>> import pyarrow as pa >>> import pandas as pd
將 Table 轉換為 pandas DataFrame
>>> table = pa.table([ ... pa.array([2, 4, 5, 100]), ... pa.array(["Flamingo", "Horse", "Brittle stars", "Centipede"]) ... ], names=['n_legs', 'animals']) >>> table.to_pandas() n_legs animals 0 2 Flamingo 1 4 Horse 2 5 Brittle stars 3 100 Centipede >>> isinstance(table.to_pandas(), pd.DataFrame) True
將 RecordBatch 轉換為 pandas DataFrame
>>> import pyarrow as pa >>> n_legs = pa.array([2, 4, 5, 100]) >>> animals = pa.array(["Flamingo", "Horse", "Brittle stars", "Centipede"]) >>> batch = pa.record_batch([n_legs, animals], ... names=["n_legs", "animals"]) >>> batch pyarrow.RecordBatch n_legs: int64 animals: string ---- n_legs: [2,4,5,100] animals: ["Flamingo","Horse","Brittle stars","Centipede"] >>> batch.to_pandas() n_legs animals 0 2 Flamingo 1 4 Horse 2 5 Brittle stars 3 100 Centipede >>> isinstance(batch.to_pandas(), pd.DataFrame) True
將 Chunked Array 轉換為 pandas Series
>>> import pyarrow as pa >>> n_legs = pa.chunked_array([[2, 2, 4], [4, 5, 100]]) >>> n_legs.to_pandas() 0 2 1 2 2 4 3 4 4 5 5 100 dtype: int64 >>> isinstance(n_legs.to_pandas(), pd.Series) True
- to_pydict(self, *, maps_as_pydicts=None)#
將 Table 或 RecordBatch 轉換為 dict 或 OrderedDict。
- 引數:
- maps_as_pydicts
str, 可選, 預設 None 有效值為 None、‘lossy’ 或 ‘strict’。預設行為 (None) 是將 Arrow Map 陣列轉換為與 Arrow Map 順序相同的原生 Python 關聯列表(元組列表),如 [(key1, value1), (key2, value2), …]。
如果為 ‘lossy’ 或 ‘strict’,則將 Arrow Map 陣列轉換為原生 Python 字典。
如果為 ‘lossy’,則每當檢測到重複鍵時,都會列印警告。重複鍵的最後看到的值將出現在 Python 字典中。如果為 ‘strict’,則會在檢測到時引發異常。
- maps_as_pydicts
- 返回:
示例
Table (RecordBatch 用法類似)
>>> import pyarrow as pa >>> n_legs = pa.array([2, 2, 4, 4, 5, 100]) >>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"]) >>> table = pa.Table.from_arrays([n_legs, animals], names=["n_legs", "animals"]) >>> table.to_pydict() {'n_legs': [2, 2, 4, 4, 5, 100], 'animals': ['Flamingo', 'Parrot', ..., 'Centipede']}
- to_pylist(self, *, maps_as_pydicts=None)#
將 Table 或 RecordBatch 轉換為行 / 字典列表。
- 引數:
- maps_as_pydicts
str, 可選, 預設 None 有效值為 None、‘lossy’ 或 ‘strict’。預設行為 (None) 是將 Arrow Map 陣列轉換為與 Arrow Map 順序相同的原生 Python 關聯列表(元組列表),如 [(key1, value1), (key2, value2), …]。
如果為 ‘lossy’ 或 ‘strict’,則將 Arrow Map 陣列轉換為原生 Python 字典。
如果為 ‘lossy’,則每當檢測到重複鍵時,都會列印警告。重複鍵的最後看到的值將出現在 Python 字典中。如果為 ‘strict’,則會在檢測到時引發異常。
- maps_as_pydicts
- 返回:
示例
Table (RecordBatch 用法類似)
>>> import pyarrow as pa >>> data = [[2, 4, 5, 100], ... ["Flamingo", "Horse", "Brittle stars", "Centipede"]] >>> table = pa.table(data, names=["n_legs", "animals"]) >>> table.to_pylist() [{'n_legs': 2, 'animals': 'Flamingo'}, {'n_legs': 4, 'animals': 'Horse'}, ...
- to_reader(self, max_chunksize=None)#
將 Table 轉換為 RecordBatchReader。
請注意,此方法是零複製的,它只是在不同的 API 下公開相同的資料。
示例
>>> import pyarrow as pa >>> table = pa.table({'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]})
將 Table 轉換為 RecordBatchReader
>>> table.to_reader() <pyarrow.lib.RecordBatchReader object at ...>
>>> reader = table.to_reader() >>> reader.schema n_legs: int64 animals: string >>> reader.read_all() pyarrow.Table n_legs: int64 animals: string ---- n_legs: [[2,4,5,100]] animals: [["Flamingo","Horse","Brittle stars","Centipede"]]
- to_string(self, *, show_metadata=False, preview_cols=0)#
返回 Table 或 RecordBatch 的人類可讀字串表示。
- to_struct_array(self, max_chunksize=None)#
轉換為結構型別的分塊陣列。
- 引數:
- 返回:
- unify_dictionaries(self, MemoryPool memory_pool=None)#
統一所有資料塊中的字典。
此方法返回一個等效的表,但其中每一列的所有資料塊(chunk)共享相同的字典值。字典索引會相應地進行轉換。
沒有字典的列將保持不變。
- 引數:
- memory_pool
MemoryPool, 預設None 用於記憶體分配(如果需要),否則使用預設記憶體池
- memory_pool
- 返回:
示例
>>> import pyarrow as pa >>> arr_1 = pa.array(["Flamingo", "Parrot", "Dog"]).dictionary_encode() >>> arr_2 = pa.array(["Horse", "Brittle stars", "Centipede"]).dictionary_encode() >>> c_arr = pa.chunked_array([arr_1, arr_2]) >>> table = pa.table([c_arr], names=["animals"]) >>> table pyarrow.Table animals: dictionary<values=string, indices=int32, ordered=0> ---- animals: [ -- dictionary: ["Flamingo","Parrot","Dog"] -- indices: [0,1,2], -- dictionary: ["Horse","Brittle stars","Centipede"] -- indices: [0,1,2]]
統一各資料塊間的字典
>>> table.unify_dictionaries() pyarrow.Table animals: dictionary<values=string, indices=int32, ordered=0> ---- animals: [ -- dictionary: ["Flamingo","Parrot","Dog","Horse","Brittle stars","Centipede"] -- indices: [0,1,2], -- dictionary: ["Flamingo","Parrot","Dog","Horse","Brittle stars","Centipede"] -- indices: [3,4,5]]