pyarrow.Table¶
- class pyarrow.Table¶
Bases:
pyarrow.lib._PandasConvertible
A collection of top-level named, equal length Arrow arrays.
Warning
Do not call this class’s constructor directly, use one of the
from_*
methods instead.- __init__(*args, **kwargs)¶
Methods
__init__
(*args, **kwargs)add_column
(self, int i, field_, column)Add column to Table at position.
append_column
(self, field_, column)Append column at end of columns.
cast
(self, Schema target_schema, bool safe=True)Cast table values to another schema.
column
(self, i)Select a column by its column name, or numeric index.
combine_chunks
(self, MemoryPool memory_pool=None)Make a new table by combining the chunks this table has.
drop
(self, columns)Drop one or more columns and return a new table.
drop_null
(self)Remove missing values from a Table.
equals
(self, Table other, ...)Check if contents of two tables are equal.
field
(self, i)Select a schema field by its column name or numeric index.
filter
(self, mask[, null_selection_behavior])Select records from a Table.
flatten
(self, MemoryPool memory_pool=None)Flatten this Table.
from_arrays
(arrays[, names, schema, metadata])Construct a Table from Arrow arrays.
from_batches
(batches, Schema schema=None)Construct a Table from a sequence or iterator of Arrow RecordBatches.
from_pandas
(type cls, df, Schema schema=None)Convert pandas.DataFrame to an Arrow Table.
from_pydict
(mapping[, schema, metadata])Construct a Table from Arrow arrays or columns.
from_pylist
(mapping[, schema, metadata])Construct a Table from list of rows / dictionaries.
get_total_buffer_size
(self)The sum of bytes in each buffer referenced by the table.
group_by
(self, keys)Declare a grouping over the columns of the table.
itercolumns
(self)Iterator over all columns in their numerical order.
remove_column
(self, int i)Create new Table with the indicated column removed.
rename_columns
(self, names)Create new table with columns renamed to provided names.
replace_schema_metadata
(self[, metadata])Create shallow copy of table by replacing schema key-value metadata with the indicated new metadata (which may be None), which deletes any existing metadata.
select
(self, columns)Select columns of the Table.
set_column
(self, int i, field_, column)Replace column in Table at position.
slice
(self[, offset, length])Compute zero-copy slice of this Table.
sort_by
(self, sorting)Sort the table by one or multiple columns.
take
(self, indices)Select records from a Table.
to_batches
(self[, max_chunksize])Convert Table to list of (contiguous) RecordBatch objects.
to_pandas
(self[, memory_pool, categories, ...])Convert to a pandas-compatible NumPy array or DataFrame, as appropriate
to_pydict
(self)Convert the Table to a dict or OrderedDict.
to_pylist
(self)Convert the Table to a list of rows / dictionaries.
to_string
(self, *[, show_metadata, preview_cols])Return human-readable string representation of Table.
unify_dictionaries
(self, ...)Unify dictionaries across all chunks.
validate
(self, *[, full])Perform validation checks.
Attributes
Names of the table's columns.
List of all columns in numerical order.
Total number of bytes consumed by the elements of the table.
Number of columns in this table.
Number of rows in this table.
Schema of the table and its columns.
Dimensions of the table: (#rows, #columns).
- add_column(self, int i, field_, column)¶
Add column to Table at position.
A new table is returned with the column added, the original table object is left unchanged.
- append_column(self, field_, column)¶
Append column at end of columns.
- cast(self, Schema target_schema, bool safe=True)¶
Cast table values to another schema.
- column(self, i)¶
Select a column by its column name, or numeric index.
- Parameters
- Returns
- columns¶
List of all columns in numerical order.
- Returns
list
ofChunkedArray
- combine_chunks(self, MemoryPool memory_pool=None)¶
Make a new table by combining the chunks this table has.
All the underlying chunks in the ChunkedArray of each column are concatenated into zero or one chunk.
- Parameters
- memory_pool
MemoryPool
, defaultNone
For memory allocations, if required, otherwise use default pool.
- memory_pool
- Returns
- drop(self, columns)¶
Drop one or more columns and return a new table.
- drop_null(self)¶
Remove missing values from a Table. See
pyarrow.compute.drop_null()
for full usage.
- equals(self, Table other, bool check_metadata=False)¶
Check if contents of two tables are equal.
- Parameters
- other
pyarrow.Table
Table to compare against.
- check_metadatabool, default
False
Whether schema metadata equality should be checked as well.
- other
- Returns
- field(self, i)¶
Select a schema field by its column name or numeric index.
- filter(self, mask, null_selection_behavior='drop')¶
Select records from a Table. See
pyarrow.compute.filter()
for full usage.
- flatten(self, MemoryPool memory_pool=None)¶
Flatten this Table.
Each column with a struct type is flattened into one column per struct field. Other columns are left unchanged.
- Parameters
- memory_pool
MemoryPool
, defaultNone
For memory allocations, if required, otherwise use default pool
- memory_pool
- Returns
- static from_arrays(arrays, names=None, schema=None, metadata=None)¶
Construct a Table from Arrow arrays.
- Parameters
- arrays
list
ofpyarrow.Array
orpyarrow.ChunkedArray
Equal-length arrays that should form the table.
- names
list
ofstr
, optional Names for the table columns. If not passed, schema must be passed.
- schema
Schema
, defaultNone
Schema for the created table. If not passed, names must be passed.
- metadata
dict
or Mapping, defaultNone
Optional metadata for the schema (if inferred).
- arrays
- Returns
- static from_batches(batches, Schema schema=None)¶
Construct a Table from a sequence or iterator of Arrow RecordBatches.
- Parameters
- batchessequence or iterator of
RecordBatch
Sequence of RecordBatch to be converted, all schemas must be equal.
- schema
Schema
, defaultNone
If not passed, will be inferred from the first RecordBatch.
- batchessequence or iterator of
- Returns
- from_pandas(type cls, df, Schema schema=None, preserve_index=None, nthreads=None, columns=None, bool safe=True)¶
Convert pandas.DataFrame to an Arrow Table.
The column types in the resulting Arrow Table are inferred from the dtypes of the pandas.Series in the DataFrame. In the case of non-object Series, the NumPy dtype is translated to its Arrow equivalent. In the case of object, we need to guess the datatype by looking at the Python objects in this Series.
Be aware that Series of the object dtype don’t carry enough information to always lead to a meaningful Arrow type. In the case that we cannot infer a type, e.g. because the DataFrame is of length 0 or the Series only contains None/nan objects, the type is set to null. This behavior can be avoided by constructing an explicit schema and passing it to this function.
- Parameters
- df
pandas.DataFrame
- schema
pyarrow.Schema
, optional The expected schema of the Arrow Table. This can be used to indicate the type of columns if we cannot infer it automatically. If passed, the output will have exactly this schema. Columns specified in the schema that are not found in the DataFrame columns or its index will raise an error. Additional columns or index levels in the DataFrame which are not specified in the schema will be ignored.
- preserve_indexbool, optional
Whether to store the index as an additional column in the resulting
Table
. The default of None will store the index as a column, except for RangeIndex which is stored as metadata only. Usepreserve_index=True
to force it to be stored as a column.- nthreads
int
, defaultNone
If greater than 1, convert columns to Arrow in parallel using indicated number of threads. By default, this follows
pyarrow.cpu_count()
(may use up to system CPU count threads).- columns
list
, optional List of column to be converted. If None, use all columns.
- safebool, default
True
Check for overflows or other unsafe conversions.
- df
- Returns
Examples
>>> import pandas as pd >>> import pyarrow as pa >>> df = pd.DataFrame({ ... 'int': [1, 2], ... 'str': ['a', 'b'] ... }) >>> pa.Table.from_pandas(df) <pyarrow.lib.Table object at 0x7f05d1fb1b40>
- static from_pydict(mapping, schema=None, metadata=None)¶
Construct a Table from Arrow arrays or columns.
- Parameters
- Returns
Examples
>>> import pyarrow as pa >>> pydict = {'int': [1, 2], 'str': ['a', 'b']} >>> pa.Table.from_pydict(pydict) pyarrow.Table int: int64 str: string ---- int: [[1,2]] str: [["a","b"]]
- static from_pylist(mapping, schema=None, metadata=None)¶
Construct a Table from list of rows / dictionaries.
- Parameters
- Returns
Examples
>>> import pyarrow as pa >>> pylist = [{'int': 1, 'str': 'a'}, {'int': 2, 'str': 'b'}] >>> pa.Table.from_pylist(pylist) pyarrow.Table int: int64 str: string ---- int: [[1,2]] str: [["a","b"]]
- get_total_buffer_size(self)¶
The sum of bytes in each buffer referenced by the table.
An array may only reference a portion of a buffer. This method will overestimate in this case and return the byte size of the entire buffer.
If a buffer is referenced multiple times then it will only be counted once.
- group_by(self, keys)¶
Declare a grouping over the columns of the table.
Resulting grouping can then be used to perform aggregations with a subsequent
aggregate()
method.- Parameters
- Returns
See also
- itercolumns(self)¶
Iterator over all columns in their numerical order.
- Yields
- nbytes¶
Total number of bytes consumed by the elements of the table.
In other words, the sum of bytes from all buffer ranges referenced.
Unlike get_total_buffer_size this method will account for array offsets.
If buffers are shared between arrays then the shared portion will only be counted multiple times.
The dictionary of dictionary arrays will always be counted in their entirety even if the array only references a portion of the dictionary.
- num_rows¶
Number of rows in this table.
Due to the definition of a table, all columns have the same number of rows.
- Returns
- remove_column(self, int i)¶
Create new Table with the indicated column removed.
- rename_columns(self, names)¶
Create new table with columns renamed to provided names.
- replace_schema_metadata(self, metadata=None)¶
Create shallow copy of table by replacing schema key-value metadata with the indicated new metadata (which may be None), which deletes any existing metadata.
- select(self, columns)¶
Select columns of the Table.
Returns a new Table with the specified columns, and metadata preserved.
- Parameters
- columnslist-like
The column names or integer indices to select.
- Returns
- set_column(self, int i, field_, column)¶
Replace column in Table at position.
- shape¶
Dimensions of the table: (#rows, #columns).
- slice(self, offset=0, length=None)¶
Compute zero-copy slice of this Table.
- sort_by(self, sorting)¶
Sort the table by one or multiple columns.
- take(self, indices)¶
Select records from a Table. See
pyarrow.compute.take()
for full usage.
- to_batches(self, max_chunksize=None, **kwargs)¶
Convert Table to list of (contiguous) RecordBatch objects.
- Parameters
- Returns
- 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, types_mapper=None)¶
Convert to a pandas-compatible NumPy array or DataFrame, as appropriate
- Parameters
- memory_pool
MemoryPool
, defaultNone
Arrow MemoryPool to use for allocations. Uses the default memory pool is not passed.
- strings_to_categoricalbool, default
False
Encode string (UTF8) and binary types to pandas.Categorical.
- categories: list, default empty
List of fields that should be returned as pandas.Categorical. Only applies to table-like data structures.
- zero_copy_onlybool, default
False
Raise an ArrowException if this function call would require copying the underlying data.
- integer_object_nullsbool, default
False
Cast integers with nulls to objects
- date_as_objectbool, default
True
Cast dates to objects. If False, convert to datetime64[ns] dtype.
- timestamp_as_objectbool, default
False
Cast non-nanosecond timestamps (np.datetime64) to objects. This is useful if you have timestamps that don’t fit in the normal date range of nanosecond timestamps (1678 CE-2262 CE). If False, all timestamps are converted to datetime64[ns] dtype.
- use_threadsbool, default
True
Whether to parallelize the conversion using multiple threads.
- deduplicate_objectsbool, default
False
Do not create multiple copies Python objects when created, to save on memory use. Conversion will be slower.
- ignore_metadatabool, default
False
If True, do not use the ‘pandas’ metadata to reconstruct the DataFrame index, if present
- safebool, default
True
For certain data types, a cast is needed in order to store the data in a pandas DataFrame or Series (e.g. timestamps are always stored as nanoseconds in pandas). This option controls whether it is a safe cast or not.
- split_blocksbool, default
False
If True, generate one internal “block” for each column when creating a pandas.DataFrame from a RecordBatch or Table. While this can temporarily reduce memory note that various pandas operations can trigger “consolidation” which may balloon memory use.
- self_destructbool, default
False
EXPERIMENTAL: If True, attempt to deallocate the originating Arrow memory while converting the Arrow object to pandas. If you use the object after calling to_pandas with this option it will crash your program.
Note that you may not see always memory usage improvements. For example, if multiple columns share an underlying allocation, memory can’t be freed until all columns are converted.
- types_mapperfunction, default
None
A function mapping a pyarrow DataType to a pandas ExtensionDtype. This can be used to override the default pandas type for conversion of built-in pyarrow types or in absence of pandas_metadata in the Table schema. The function receives a pyarrow DataType and is expected to return a pandas ExtensionDtype or
None
if the default conversion should be used for that type. If you have a dictionary mapping, you can passdict.get
as function.
- memory_pool
- Returns
pandas.Series
orpandas.DataFrame
depending ontype
of object
- to_pydict(self)¶
Convert the Table to a dict or OrderedDict.
- Returns
Examples
>>> import pyarrow as pa >>> table = pa.table([ ... pa.array([1, 2]), ... pa.array(["a", "b"]) ... ], names=["int", "str"]) >>> table.to_pydict() {'int': [1, 2], 'str': ['a', 'b']}
- to_pylist(self)¶
Convert the Table to a list of rows / dictionaries.
- Returns
Examples
>>> import pyarrow as pa >>> table = pa.table([ ... pa.array([1, 2]), ... pa.array(["a", "b"]) ... ], names=["int", "str"]) >>> table.to_pylist() [{'int': 1, 'str': 'a'}, {'int': 2, 'str': 'b'}]
- to_string(self, *, show_metadata=False, preview_cols=0)¶
Return human-readable string representation of Table.
- unify_dictionaries(self, MemoryPool memory_pool=None)¶
Unify dictionaries across all chunks.
This method returns an equivalent table, but where all chunks of each column share the same dictionary values. Dictionary indices are transposed accordingly.
Columns without dictionaries are returned unchanged.
- Parameters
- memory_pool
MemoryPool
, defaultNone
For memory allocations, if required, otherwise use default pool
- memory_pool
- Returns
- validate(self, *, full=False)¶
Perform validation checks. An exception is raised if validation fails.
By default only cheap validation checks are run. Pass full=True for thorough validation checks (potentially O(n)).
- Parameters
- full: bool, default False
If True, run expensive checks, otherwise cheap checks only.
- Raises
ArrowInvalid