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

column_names

Names of the table's columns.

columns

List of all columns in numerical order.

nbytes

Total number of bytes consumed by the elements of the table.

num_columns

Number of columns in this table.

num_rows

Number of rows in this table.

schema

Schema of the table and its columns.

shape

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.

Parameters
iint

Index to place the column at.

field_str or Field

If a string is passed then the type is deduced from the column data.

columnArray, list of Array, or values coercible to arrays

Column data.

Returns
Table

New table with the passed column added.

append_column(self, field_, column)

Append column at end of columns.

Parameters
field_str or Field

If a string is passed then the type is deduced from the column data.

columnArray, list of Array, or values coercible to arrays

Column data.

Returns
Table

New table with the passed column added.

cast(self, Schema target_schema, bool safe=True)

Cast table values to another schema.

Parameters
target_schemaSchema

Schema to cast to, the names and order of fields must match.

safebool, default True

Check for overflows or other unsafe conversions.

Returns
Table
column(self, i)

Select a column by its column name, or numeric index.

Parameters
iint or str

The index or name of the column to retrieve.

Returns
ChunkedArray
column_names

Names of the table’s columns.

Returns
list of str
columns

List of all columns in numerical order.

Returns
list of ChunkedArray
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_poolMemoryPool, default None

For memory allocations, if required, otherwise use default pool.

Returns
Table
drop(self, columns)

Drop one or more columns and return a new table.

Parameters
columnslist of str

List of field names referencing existing columns.

Returns
Table

New table without the columns.

Raises
KeyError

If any of the passed columns name are not existing.

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
otherpyarrow.Table

Table to compare against.

check_metadatabool, default False

Whether schema metadata equality should be checked as well.

Returns
bool
field(self, i)

Select a schema field by its column name or numeric index.

Parameters
iint or str

The index or name of the field to retrieve.

Returns
Field
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_poolMemoryPool, default None

For memory allocations, if required, otherwise use default pool

Returns
Table
static from_arrays(arrays, names=None, schema=None, metadata=None)

Construct a Table from Arrow arrays.

Parameters
arrayslist of pyarrow.Array or pyarrow.ChunkedArray

Equal-length arrays that should form the table.

nameslist of str, optional

Names for the table columns. If not passed, schema must be passed.

schemaSchema, default None

Schema for the created table. If not passed, names must be passed.

metadatadict or Mapping, default None

Optional metadata for the schema (if inferred).

Returns
Table
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.

schemaSchema, default None

If not passed, will be inferred from the first RecordBatch.

Returns
Table
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
dfpandas.DataFrame
schemapyarrow.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. Use preserve_index=True to force it to be stored as a column.

nthreadsint, default None

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).

columnslist, optional

List of column to be converted. If None, use all columns.

safebool, default True

Check for overflows or other unsafe conversions.

Returns
Table

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
mappingdict or Mapping

A mapping of strings to Arrays or Python lists.

schemaSchema, default None

If not passed, will be inferred from the Mapping values.

metadatadict or Mapping, default None

Optional metadata for the schema (if inferred).

Returns
Table

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
mappinglist of dicts of rows

A mapping of strings to row values.

schemaSchema, default None

If not passed, will be inferred from the first row of the mapping values.

metadatadict or Mapping, default None

Optional metadata for the schema (if inferred).

Returns
Table

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
keysstr or list[str]

Name of the columns that should be used as the grouping key.

Returns
TableGroupBy
itercolumns(self)

Iterator over all columns in their numerical order.

Yields
ChunkedArray
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_columns

Number of columns in this table.

Returns
int
num_rows

Number of rows in this table.

Due to the definition of a table, all columns have the same number of rows.

Returns
int
remove_column(self, int i)

Create new Table with the indicated column removed.

Parameters
iint

Index of column to remove.

Returns
Table

New table without the column.

rename_columns(self, names)

Create new table with columns renamed to provided names.

Parameters
nameslist of str

List of new column names.

Returns
Table
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.

Parameters
metadatadict, default None
Returns
Table
schema

Schema of the table and its columns.

Returns
Schema
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
Table
set_column(self, int i, field_, column)

Replace column in Table at position.

Parameters
iint

Index to place the column at.

field_str or Field

If a string is passed then the type is deduced from the column data.

columnArray, list of Array, or values coercible to arrays

Column data.

Returns
Table

New table with the passed column set.

shape

Dimensions of the table: (#rows, #columns).

Returns
(int, int)

Number of rows and number of columns.

slice(self, offset=0, length=None)

Compute zero-copy slice of this Table.

Parameters
offsetint, default 0

Offset from start of table to slice.

lengthint, default None

Length of slice (default is until end of table starting from offset).

Returns
Table
sort_by(self, sorting)

Sort the table by one or multiple columns.

Parameters
sortingstr or list[tuple(name, order)]

Name of the column to use to sort (ascending), or a list of multiple sorting conditions where each entry is a tuple with column name and sorting order (“ascending” or “descending”)

Returns
Table

A new table sorted according to the sort keys.

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
max_chunksizeint, default None

Maximum size for RecordBatch chunks. Individual chunks may be smaller depending on the chunk layout of individual columns.

Returns
list[RecordBatch]
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_poolMemoryPool, default None

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 pass dict.get as function.

Returns
pandas.Series or pandas.DataFrame depending on type of object
to_pydict(self)

Convert the Table to a dict or OrderedDict.

Returns
dict

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
list

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.

Parameters
show_metadatabool, default False

Display Field-level and Schema-level KeyValueMetadata.

preview_colsint, default 0

Display values of the columns for the first N columns.

Returns
str
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_poolMemoryPool, default None

For memory allocations, if required, otherwise use default pool

Returns
Table
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