From f6daac294e89227e8f9d5e96c166f38bbd7f861e Mon Sep 17 00:00:00 2001 From: Dane Pitkin Date: Fri, 7 Apr 2023 15:51:32 -0400 Subject: [PATCH 1/7] GH-34979: [Python] Create a base class for Table and RecordBatch --- python/pyarrow/lib.pxd | 8 ++- python/pyarrow/table.pxi | 125 ++++++++++++++++++--------------------- 2 files changed, 62 insertions(+), 71 deletions(-) diff --git a/python/pyarrow/lib.pxd b/python/pyarrow/lib.pxd index d984475171f0..30f24fc340c4 100644 --- a/python/pyarrow/lib.pxd +++ b/python/pyarrow/lib.pxd @@ -469,7 +469,11 @@ cdef class ChunkedArray(_PandasConvertible): cdef getitem(self, int64_t i) -cdef class Table(_PandasConvertible): +cdef class _Table(_PandasConvertible): + pass + + +cdef class Table(_Table): cdef: shared_ptr[CTable] sp_table CTable* table @@ -477,7 +481,7 @@ cdef class Table(_PandasConvertible): cdef void init(self, const shared_ptr[CTable]& table) -cdef class RecordBatch(_PandasConvertible): +cdef class RecordBatch(_Table): cdef: shared_ptr[CRecordBatch] sp_batch CRecordBatch* batch diff --git a/python/pyarrow/table.pxi b/python/pyarrow/table.pxi index ede3c39ca963..105d7b15910e 100644 --- a/python/pyarrow/table.pxi +++ b/python/pyarrow/table.pxi @@ -1450,8 +1450,62 @@ cdef _sanitize_arrays(arrays, names, schema, metadata, converted_arrays.append(item) return converted_arrays +cdef class _Table(_PandasConvertible): + """Internal: An interface for common table operations.""" -cdef class RecordBatch(_PandasConvertible): + def take(self, object indices): + """ + Select rows from the table or record batch. + + See :func:`pyarrow.compute.take` for full usage. + + Parameters + ---------- + indices : Array or array-like + The indices in the table whose rows will be returned. + + Returns + ------- + taken : Table or RecordBatch + A table or record batch with the same schema, containing the taken rows. + + Examples + -------- + Table example + + >>> import pyarrow as pa + >>> import pandas as pd + >>> df = pd.DataFrame(dict('year': [2020, 2022, 2019, 2021], + ... 'n_legs': [2, 4, 5, 100], + ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"])) + >>> table = pa.Table.from_pandas(df) + >>> table.take([1,3]) + pyarrow.Table + year: int64 + n_legs: int64 + animals: string + ---- + year: [[2022,2021]] + n_legs: [[4,100]] + animals: [["Horse","Centipede"]] + + RecordBatch example + + >>> import pyarrow as pa + >>> n_legs = pa.array([2, 2, 4, 4, 5, 100]) + >>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"]) + >>> batch = pa.RecordBatch.from_arrays([n_legs, animals], + ... names=["n_legs", "animals"]) + >>> batch.take([1,3,4]).to_pandas() + n_legs animals + 0 2 Parrot + 1 4 Horse + 2 5 Brittle stars + """ + return _pc().take(self, indices) + + +cdef class RecordBatch(_Table): """ Batch of rows of columns of equal length @@ -2254,37 +2308,6 @@ cdef class RecordBatch(_PandasConvertible): return result - def take(self, object indices): - """ - Select rows from the record batch. - - See :func:`pyarrow.compute.take` for full usage. - - Parameters - ---------- - indices : Array or array-like - The indices in the record batch whose rows will be returned. - - Returns - ------- - taken : RecordBatch - A record batch with the same schema, containing the taken rows. - - Examples - -------- - >>> import pyarrow as pa - >>> n_legs = pa.array([2, 2, 4, 4, 5, 100]) - >>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"]) - >>> batch = pa.RecordBatch.from_arrays([n_legs, animals], - ... names=["n_legs", "animals"]) - >>> batch.take([1,3,4]).to_pandas() - n_legs animals - 0 2 Parrot - 1 4 Horse - 2 5 Brittle stars - """ - return _pc().take(self, indices) - def drop_null(self): """ Remove missing values from a RecordBatch. @@ -2776,7 +2799,7 @@ def table_to_blocks(options, Table table, categories, extension_columns): return PyObject_to_object(result_obj) -cdef class Table(_PandasConvertible): +cdef class Table(_Table): """ A collection of top-level named, equal length Arrow arrays. @@ -3153,42 +3176,6 @@ cdef class Table(_PandasConvertible): else: return _pc().filter(self, mask, null_selection_behavior) - def take(self, object indices): - """ - Select rows from the table. - - See :func:`pyarrow.compute.take` for full usage. - - Parameters - ---------- - indices : Array or array-like - The indices in the table whose rows will be returned. - - Returns - ------- - taken : Table - A table with the same schema, containing the taken rows. - - Examples - -------- - >>> 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) - >>> table.take([1,3]) - pyarrow.Table - year: int64 - n_legs: int64 - animals: string - ---- - year: [[2022,2021]] - n_legs: [[4,100]] - animals: [["Horse","Centipede"]] - """ - return _pc().take(self, indices) - def drop_null(self): """ Remove missing values from a Table. From 148bae6ea1900be30a4b4a53523b1e7a8423135a Mon Sep 17 00:00:00 2001 From: Dane Pitkin Date: Fri, 7 Apr 2023 16:37:55 -0400 Subject: [PATCH 2/7] Move docstrings to subsclasses --- python/pyarrow/table.pxi | 115 +++++++++++++++++++++++---------------- 1 file changed, 67 insertions(+), 48 deletions(-) diff --git a/python/pyarrow/table.pxi b/python/pyarrow/table.pxi index 105d7b15910e..93ba77d732da 100644 --- a/python/pyarrow/table.pxi +++ b/python/pyarrow/table.pxi @@ -1454,54 +1454,6 @@ cdef class _Table(_PandasConvertible): """Internal: An interface for common table operations.""" def take(self, object indices): - """ - Select rows from the table or record batch. - - See :func:`pyarrow.compute.take` for full usage. - - Parameters - ---------- - indices : Array or array-like - The indices in the table whose rows will be returned. - - Returns - ------- - taken : Table or RecordBatch - A table or record batch with the same schema, containing the taken rows. - - Examples - -------- - Table example - - >>> import pyarrow as pa - >>> import pandas as pd - >>> df = pd.DataFrame(dict('year': [2020, 2022, 2019, 2021], - ... 'n_legs': [2, 4, 5, 100], - ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"])) - >>> table = pa.Table.from_pandas(df) - >>> table.take([1,3]) - pyarrow.Table - year: int64 - n_legs: int64 - animals: string - ---- - year: [[2022,2021]] - n_legs: [[4,100]] - animals: [["Horse","Centipede"]] - - RecordBatch example - - >>> import pyarrow as pa - >>> n_legs = pa.array([2, 2, 4, 4, 5, 100]) - >>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"]) - >>> batch = pa.RecordBatch.from_arrays([n_legs, animals], - ... names=["n_legs", "animals"]) - >>> batch.take([1,3,4]).to_pandas() - n_legs animals - 0 2 Parrot - 1 4 Horse - 2 5 Brittle stars - """ return _pc().take(self, indices) @@ -2308,6 +2260,37 @@ cdef class RecordBatch(_Table): return result + def take(self, object indices): + """ + Select rows from the record batch. + + See :func:`pyarrow.compute.take` for full usage. + + Parameters + ---------- + indices : Array or array-like + The indices in the record batch whose rows will be returned. + + Returns + ------- + taken : RecordBatch + A record batch with the same schema, containing the taken rows. + + Examples + -------- + >>> import pyarrow as pa + >>> n_legs = pa.array([2, 2, 4, 4, 5, 100]) + >>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"]) + >>> batch = pa.RecordBatch.from_arrays([n_legs, animals], + ... names=["n_legs", "animals"]) + >>> batch.take([1,3,4]).to_pandas() + n_legs animals + 0 2 Parrot + 1 4 Horse + 2 5 Brittle stars + """ + return super().take(indices) + def drop_null(self): """ Remove missing values from a RecordBatch. @@ -3176,6 +3159,42 @@ cdef class Table(_Table): else: return _pc().filter(self, mask, null_selection_behavior) + def take(self, object indices): + """ + Select rows from the table. + + See :func:`pyarrow.compute.take` for full usage. + + Parameters + ---------- + indices : Array or array-like + The indices in the table whose rows will be returned. + + Returns + ------- + taken : Table + A table with the same schema, containing the taken rows. + + Examples + -------- + >>> 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) + >>> table.take([1,3]) + pyarrow.Table + year: int64 + n_legs: int64 + animals: string + ---- + year: [[2022,2021]] + n_legs: [[4,100]] + animals: [["Horse","Centipede"]] + """ + return super().take(indices) + def drop_null(self): """ Remove missing values from a Table. From b1287d0cd90c2fddeb68fd796e71b639c9e39b86 Mon Sep 17 00:00:00 2001 From: Dane Pitkin Date: Fri, 7 Apr 2023 17:02:17 -0400 Subject: [PATCH 3/7] Add init method --- python/pyarrow/table.pxi | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/python/pyarrow/table.pxi b/python/pyarrow/table.pxi index 93ba77d732da..d306c4977201 100644 --- a/python/pyarrow/table.pxi +++ b/python/pyarrow/table.pxi @@ -1453,6 +1453,10 @@ cdef _sanitize_arrays(arrays, names, schema, metadata, cdef class _Table(_PandasConvertible): """Internal: An interface for common table operations.""" + def __init__(self): + raise TypeError("This object is not instantiable, " + "use a subclass instead.") + def take(self, object indices): return _pc().take(self, indices) From bb72dc9315d72fdfd383be7bb6ffc95bcd29e137 Mon Sep 17 00:00:00 2001 From: Dane Pitkin Date: Tue, 11 Apr 2023 15:51:11 -0400 Subject: [PATCH 4/7] Use shared docstrings, move second shared compute func to base class --- python/pyarrow/table.pxi | 180 +++++++++++++-------------------------- 1 file changed, 58 insertions(+), 122 deletions(-) diff --git a/python/pyarrow/table.pxi b/python/pyarrow/table.pxi index d306c4977201..3bd6739810d0 100644 --- a/python/pyarrow/table.pxi +++ b/python/pyarrow/table.pxi @@ -1457,7 +1457,65 @@ cdef class _Table(_PandasConvertible): raise TypeError("This object is not instantiable, " "use a subclass instead.") + def drop_null(self): + """ + Remove missing values from a Table. + See :func:`pyarrow.compute.drop_null` for full usage. + + Examples + -------- + >>> import pyarrow as pa + >>> import pandas as pd + >>> df = pd.DataFrame({'year': [None, 2022, 2019, 2021], + ... 'n_legs': [2, 4, 5, 100], + ... 'animals': ["Flamingo", "Horse", None, "Centipede"]}) + >>> table = pa.Table.from_pandas(df) + >>> table.drop_null() + pyarrow.Table + year: double + n_legs: int64 + animals: string + ---- + year: [[2022,2021]] + n_legs: [[4,100]] + animals: [["Horse","Centipede"]] + """ + return _pc().drop_null(self) + def take(self, object indices): + """ + Select rows from the table. + + See :func:`pyarrow.compute.take` for full usage. + + Parameters + ---------- + indices : Array or array-like + The indices in the table whose rows will be returned. + + Returns + ------- + taken : Table + A table with the same schema, containing the taken rows. + + Examples + -------- + >>> 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) + >>> table.take([1,3]) + pyarrow.Table + year: int64 + n_legs: int64 + animals: string + ---- + year: [[2022,2021]] + n_legs: [[4,100]] + animals: [["Horse","Centipede"]] + """ return _pc().take(self, indices) @@ -2264,67 +2322,6 @@ cdef class RecordBatch(_Table): return result - def take(self, object indices): - """ - Select rows from the record batch. - - See :func:`pyarrow.compute.take` for full usage. - - Parameters - ---------- - indices : Array or array-like - The indices in the record batch whose rows will be returned. - - Returns - ------- - taken : RecordBatch - A record batch with the same schema, containing the taken rows. - - Examples - -------- - >>> import pyarrow as pa - >>> n_legs = pa.array([2, 2, 4, 4, 5, 100]) - >>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", "Brittle stars", "Centipede"]) - >>> batch = pa.RecordBatch.from_arrays([n_legs, animals], - ... names=["n_legs", "animals"]) - >>> batch.take([1,3,4]).to_pandas() - n_legs animals - 0 2 Parrot - 1 4 Horse - 2 5 Brittle stars - """ - return super().take(indices) - - def drop_null(self): - """ - Remove missing values from a RecordBatch. - See :func:`pyarrow.compute.drop_null` for full usage. - - Examples - -------- - >>> import pyarrow as pa - >>> n_legs = pa.array([2, 2, 4, 4, 5, 100]) - >>> animals = pa.array(["Flamingo", "Parrot", "Dog", "Horse", None, "Centipede"]) - >>> batch = pa.RecordBatch.from_arrays([n_legs, animals], - ... names=["n_legs", "animals"]) - >>> batch.to_pandas() - n_legs animals - 0 2 Flamingo - 1 2 Parrot - 2 4 Dog - 3 4 Horse - 4 5 None - 5 100 Centipede - >>> batch.drop_null().to_pandas() - n_legs animals - 0 2 Flamingo - 1 2 Parrot - 2 4 Dog - 3 4 Horse - 4 100 Centipede - """ - return _pc().drop_null(self) - def select(self, object columns): """ Select columns of the RecordBatch. @@ -3163,67 +3160,6 @@ cdef class Table(_Table): else: return _pc().filter(self, mask, null_selection_behavior) - def take(self, object indices): - """ - Select rows from the table. - - See :func:`pyarrow.compute.take` for full usage. - - Parameters - ---------- - indices : Array or array-like - The indices in the table whose rows will be returned. - - Returns - ------- - taken : Table - A table with the same schema, containing the taken rows. - - Examples - -------- - >>> 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) - >>> table.take([1,3]) - pyarrow.Table - year: int64 - n_legs: int64 - animals: string - ---- - year: [[2022,2021]] - n_legs: [[4,100]] - animals: [["Horse","Centipede"]] - """ - return super().take(indices) - - def drop_null(self): - """ - Remove missing values from a Table. - See :func:`pyarrow.compute.drop_null` for full usage. - - Examples - -------- - >>> import pyarrow as pa - >>> import pandas as pd - >>> df = pd.DataFrame({'year': [None, 2022, 2019, 2021], - ... 'n_legs': [2, 4, 5, 100], - ... 'animals': ["Flamingo", "Horse", None, "Centipede"]}) - >>> table = pa.Table.from_pandas(df) - >>> table.drop_null() - pyarrow.Table - year: double - n_legs: int64 - animals: string - ---- - year: [[2022,2021]] - n_legs: [[4,100]] - animals: [["Horse","Centipede"]] - """ - return _pc().drop_null(self) - def select(self, object columns): """ Select columns of the Table. From daa562c8795b5fcf3f97fa6dfa4c926f3dfa9ad0 Mon Sep 17 00:00:00 2001 From: Dane Pitkin Date: Thu, 13 Apr 2023 16:35:34 -0400 Subject: [PATCH 5/7] Update Base class name, update docstrings with more examples --- python/pyarrow/lib.pxd | 6 ++-- python/pyarrow/table.pxi | 75 ++++++++++++++++++++++++++++++++++------ 2 files changed, 67 insertions(+), 14 deletions(-) diff --git a/python/pyarrow/lib.pxd b/python/pyarrow/lib.pxd index 30f24fc340c4..4c0c8c4f083a 100644 --- a/python/pyarrow/lib.pxd +++ b/python/pyarrow/lib.pxd @@ -469,11 +469,11 @@ cdef class ChunkedArray(_PandasConvertible): cdef getitem(self, int64_t i) -cdef class _Table(_PandasConvertible): +cdef class _Tabular(_PandasConvertible): pass -cdef class Table(_Table): +cdef class Table(_Tabular): cdef: shared_ptr[CTable] sp_table CTable* table @@ -481,7 +481,7 @@ cdef class Table(_Table): cdef void init(self, const shared_ptr[CTable]& table) -cdef class RecordBatch(_Table): +cdef class RecordBatch(_Tabular): cdef: shared_ptr[CRecordBatch] sp_batch CRecordBatch* batch diff --git a/python/pyarrow/table.pxi b/python/pyarrow/table.pxi index 3bd6739810d0..01b0f5e37231 100644 --- a/python/pyarrow/table.pxi +++ b/python/pyarrow/table.pxi @@ -1450,8 +1450,8 @@ cdef _sanitize_arrays(arrays, names, schema, metadata, converted_arrays.append(item) return converted_arrays -cdef class _Table(_PandasConvertible): - """Internal: An interface for common table operations.""" +cdef class _Tabular(_PandasConvertible): + """Internal: An interface for common operations on tabular objects.""" def __init__(self): raise TypeError("This object is not instantiable, " @@ -1459,18 +1459,29 @@ cdef class _Table(_PandasConvertible): def drop_null(self): """ - Remove missing values from a Table. + Remove rows that contain missing values from a Table or RecordBatch. + See :func:`pyarrow.compute.drop_null` for full usage. + Returns + ------- + Table or RecordBatch + A tabular object with the same schema, with rows containing + no missing values. + Examples -------- + + Table + >>> import pyarrow as pa >>> import pandas as pd >>> df = pd.DataFrame({'year': [None, 2022, 2019, 2021], ... 'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", None, "Centipede"]}) >>> table = pa.Table.from_pandas(df) - >>> table.drop_null() + >>> table = table.drop_null() + >>> table pyarrow.Table year: double n_legs: int64 @@ -1479,34 +1490,57 @@ cdef class _Table(_PandasConvertible): year: [[2022,2021]] n_legs: [[4,100]] animals: [["Horse","Centipede"]] + + RecordBatch + + >>> recordbatch = pa.RecordBatch.from_pandas(df) + >>> recordbatch = recordbatch.drop_null() + >>> recordbatch.columns + [ + [ + 2022, + 2021 + ], + [ + 4, + 100 + ], + [ + "Horse", + "Centipede" + ]] """ return _pc().drop_null(self) def take(self, object indices): """ - Select rows from the table. + Select rows from a Table or RecordBatch. See :func:`pyarrow.compute.take` for full usage. Parameters ---------- indices : Array or array-like - The indices in the table whose rows will be returned. + The indices in the tabular object whose rows will be returned. Returns ------- - taken : Table - A table with the same schema, containing the taken rows. + Table or RecordBatch + A tabular object with the same schema, containing the taken rows. Examples -------- + + Table + >>> 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) - >>> table.take([1,3]) + >>> table = table.take([1,3]) + >>> table pyarrow.Table year: int64 n_legs: int64 @@ -1515,11 +1549,30 @@ cdef class _Table(_PandasConvertible): year: [[2022,2021]] n_legs: [[4,100]] animals: [["Horse","Centipede"]] + + RecordBatch + + >>> recordbatch = pa.RecordBatch.from_pandas(df) + >>> recordbatch = recordbatch.take([1,3]) + >>> recordbatch.columns + [ + [ + 2022, + 2021 + ], + [ + 4, + 100 + ], + [ + "Horse", + "Centipede" + ]] """ return _pc().take(self, indices) -cdef class RecordBatch(_Table): +cdef class RecordBatch(_Tabular): """ Batch of rows of columns of equal length @@ -2783,7 +2836,7 @@ def table_to_blocks(options, Table table, categories, extension_columns): return PyObject_to_object(result_obj) -cdef class Table(_Table): +cdef class Table(_Tabular): """ A collection of top-level named, equal length Arrow arrays. From 2b44da785b5606ca7d020fe6248036e73761059c Mon Sep 17 00:00:00 2001 From: Dane Pitkin Date: Thu, 13 Apr 2023 17:42:55 -0400 Subject: [PATCH 6/7] Add __repr__ and to_string methods for identical outputs --- python/pyarrow/table.pxi | 186 +++++++++++++++++++++------------------ 1 file changed, 99 insertions(+), 87 deletions(-) diff --git a/python/pyarrow/table.pxi b/python/pyarrow/table.pxi index 01b0f5e37231..d076110e7f43 100644 --- a/python/pyarrow/table.pxi +++ b/python/pyarrow/table.pxi @@ -1457,6 +1457,15 @@ cdef class _Tabular(_PandasConvertible): raise TypeError("This object is not instantiable, " "use a subclass instead.") + def __repr__(self): + if not self._is_initialized(): + raise ValueError("This object's internal pointer is NULL, do not " + "use any methods or attributes on this object") + return self.to_string(preview_cols=10) + + def _is_initialized(self): + raise NotImplementedError + def drop_null(self): """ Remove rows that contain missing values from a Table or RecordBatch. @@ -1471,8 +1480,7 @@ cdef class _Tabular(_PandasConvertible): Examples -------- - - Table + Table (also works identically for RecordBatch) >>> import pyarrow as pa >>> import pandas as pd @@ -1480,8 +1488,7 @@ cdef class _Tabular(_PandasConvertible): ... 'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", None, "Centipede"]}) >>> table = pa.Table.from_pandas(df) - >>> table = table.drop_null() - >>> table + >>> table.drop_null() pyarrow.Table year: double n_legs: int64 @@ -1490,25 +1497,6 @@ cdef class _Tabular(_PandasConvertible): year: [[2022,2021]] n_legs: [[4,100]] animals: [["Horse","Centipede"]] - - RecordBatch - - >>> recordbatch = pa.RecordBatch.from_pandas(df) - >>> recordbatch = recordbatch.drop_null() - >>> recordbatch.columns - [ - [ - 2022, - 2021 - ], - [ - 4, - 100 - ], - [ - "Horse", - "Centipede" - ]] """ return _pc().drop_null(self) @@ -1539,8 +1527,7 @@ cdef class _Tabular(_PandasConvertible): ... 'n_legs': [2, 4, 5, 100], ... 'animals': ["Flamingo", "Horse", "Brittle stars", "Centipede"]}) >>> table = pa.Table.from_pandas(df) - >>> table = table.take([1,3]) - >>> table + >>> table.take([1,3]) pyarrow.Table year: int64 n_legs: int64 @@ -1553,24 +1540,43 @@ cdef class _Tabular(_PandasConvertible): RecordBatch >>> recordbatch = pa.RecordBatch.from_pandas(df) - >>> recordbatch = recordbatch.take([1,3]) - >>> recordbatch.columns - [ - [ - 2022, - 2021 - ], - [ - 4, - 100 - ], - [ - "Horse", - "Centipede" - ]] + >>> recordbatch.take([1,3]) """ return _pc().take(self, indices) + def to_string(self, *, show_metadata=False, preview_cols=0): + """ + Return human-readable string representation of Table or RecordBatch. + + Parameters + ---------- + show_metadata : bool, default False + Display Field-level and Schema-level KeyValueMetadata. + preview_cols : int, default 0 + Display values of the columns for the first N columns. + + Returns + ------- + str + """ + # Use less verbose schema output. + schema_as_string = self.schema.to_string( + show_field_metadata=show_metadata, + show_schema_metadata=show_metadata + ) + title = 'pyarrow.{}\n{}'.format(type(self).__name__, schema_as_string) + pieces = [title] + if preview_cols: + pieces.append('----') + for i in range(min(self.num_columns, preview_cols)): + pieces.append('{}: {}'.format( + self.field(i).name, + self.column(i).to_string(indent=0, skip_new_lines=True) + )) + if preview_cols < self.num_columns: + pieces.append('...') + return '\n'.join(pieces) + cdef class RecordBatch(_Tabular): """ @@ -1666,6 +1672,9 @@ cdef class RecordBatch(_Tabular): self.sp_batch = batch self.batch = batch.get() + def _is_initialized(self): + return self.batch != NULL + # ---------------------------------------------------------------------- def __dataframe__(self, nan_as_null: bool = False, allow_copy: bool = True): """ @@ -1817,16 +1826,16 @@ cdef class RecordBatch(_Tabular): except TypeError: return NotImplemented - def to_string(self, show_metadata=False): - # Use less verbose schema output. - schema_as_string = self.schema.to_string( - show_field_metadata=show_metadata, - show_schema_metadata=show_metadata - ) - return 'pyarrow.{}\n{}'.format(type(self).__name__, schema_as_string) + # def to_string(self, show_metadata=False): + # # Use less verbose schema output. + # schema_as_string = self.schema.to_string( + # show_field_metadata=show_metadata, + # show_schema_metadata=show_metadata + # ) + # return 'pyarrow.{}\n{}'.format(type(self).__name__, schema_as_string) - def __repr__(self): - return self.to_string() + # def __repr__(self): + # return self.to_string() def validate(self, *, full=False): """ @@ -2955,49 +2964,52 @@ cdef class Table(_Tabular): raise TypeError("Do not call Table's constructor directly, use one of " "the `Table.from_*` functions instead.") - def to_string(self, *, show_metadata=False, preview_cols=0): - """ - Return human-readable string representation of Table. - - Parameters - ---------- - show_metadata : bool, default False - Display Field-level and Schema-level KeyValueMetadata. - preview_cols : int, default 0 - Display values of the columns for the first N columns. - - Returns - ------- - str - """ - # Use less verbose schema output. - schema_as_string = self.schema.to_string( - show_field_metadata=show_metadata, - show_schema_metadata=show_metadata - ) - title = 'pyarrow.{}\n{}'.format(type(self).__name__, schema_as_string) - pieces = [title] - if preview_cols: - pieces.append('----') - for i in range(min(self.num_columns, preview_cols)): - pieces.append('{}: {}'.format( - self.field(i).name, - self.column(i).to_string(indent=0, skip_new_lines=True) - )) - if preview_cols < self.num_columns: - pieces.append('...') - return '\n'.join(pieces) - - def __repr__(self): - if self.table == NULL: - raise ValueError("Table's internal pointer is NULL, do not use " - "any methods or attributes on this object") - return self.to_string(preview_cols=10) + # def to_string(self, *, show_metadata=False, preview_cols=0): + # """ + # Return human-readable string representation of Table. + + # Parameters + # ---------- + # show_metadata : bool, default False + # Display Field-level and Schema-level KeyValueMetadata. + # preview_cols : int, default 0 + # Display values of the columns for the first N columns. + + # Returns + # ------- + # str + # """ + # # Use less verbose schema output. + # schema_as_string = self.schema.to_string( + # show_field_metadata=show_metadata, + # show_schema_metadata=show_metadata + # ) + # title = 'pyarrow.{}\n{}'.format(type(self).__name__, schema_as_string) + # pieces = [title] + # if preview_cols: + # pieces.append('----') + # for i in range(min(self.num_columns, preview_cols)): + # pieces.append('{}: {}'.format( + # self.field(i).name, + # self.column(i).to_string(indent=0, skip_new_lines=True) + # )) + # if preview_cols < self.num_columns: + # pieces.append('...') + # return '\n'.join(pieces) + + # def __repr__(self): + # if self.table == NULL: + # raise ValueError("Table's internal pointer is NULL, do not use " + # "any methods or attributes on this object") + # return self.to_string(preview_cols=10) cdef void init(self, const shared_ptr[CTable]& table): self.sp_table = table self.table = table.get() + def _is_initialized(self): + return self.table != NULL + def validate(self, *, full=False): """ Perform validation checks. An exception is raised if validation fails. From d771c6a9f19c0c75f3d18d31fa6f1a37b833863d Mon Sep 17 00:00:00 2001 From: Dane Pitkin Date: Thu, 13 Apr 2023 19:13:05 -0400 Subject: [PATCH 7/7] Fix tests, remove commented code --- python/pyarrow/table.pxi | 64 +++++----------------------------------- 1 file changed, 7 insertions(+), 57 deletions(-) diff --git a/python/pyarrow/table.pxi b/python/pyarrow/table.pxi index d076110e7f43..d902a661c7af 100644 --- a/python/pyarrow/table.pxi +++ b/python/pyarrow/table.pxi @@ -1480,7 +1480,7 @@ cdef class _Tabular(_PandasConvertible): Examples -------- - Table (also works identically for RecordBatch) + Table (works similarly for RecordBatch) >>> import pyarrow as pa >>> import pandas as pd @@ -1518,8 +1518,7 @@ cdef class _Tabular(_PandasConvertible): Examples -------- - - Table + Table (works similarly for RecordBatch) >>> import pyarrow as pa >>> import pandas as pd @@ -1536,11 +1535,6 @@ cdef class _Tabular(_PandasConvertible): year: [[2022,2021]] n_legs: [[4,100]] animals: [["Horse","Centipede"]] - - RecordBatch - - >>> recordbatch = pa.RecordBatch.from_pandas(df) - >>> recordbatch.take([1,3]) """ return _pc().take(self, indices) @@ -1826,16 +1820,11 @@ cdef class RecordBatch(_Tabular): except TypeError: return NotImplemented - # def to_string(self, show_metadata=False): - # # Use less verbose schema output. - # schema_as_string = self.schema.to_string( - # show_field_metadata=show_metadata, - # show_schema_metadata=show_metadata - # ) - # return 'pyarrow.{}\n{}'.format(type(self).__name__, schema_as_string) - - # def __repr__(self): - # return self.to_string() + def __repr__(self): + # TODO remove this and update pytests/doctests for + # RecordBatch.to_string(preview_cols=10) usage in + # parent class + return self.to_string() def validate(self, *, full=False): """ @@ -2964,45 +2953,6 @@ cdef class Table(_Tabular): raise TypeError("Do not call Table's constructor directly, use one of " "the `Table.from_*` functions instead.") - # def to_string(self, *, show_metadata=False, preview_cols=0): - # """ - # Return human-readable string representation of Table. - - # Parameters - # ---------- - # show_metadata : bool, default False - # Display Field-level and Schema-level KeyValueMetadata. - # preview_cols : int, default 0 - # Display values of the columns for the first N columns. - - # Returns - # ------- - # str - # """ - # # Use less verbose schema output. - # schema_as_string = self.schema.to_string( - # show_field_metadata=show_metadata, - # show_schema_metadata=show_metadata - # ) - # title = 'pyarrow.{}\n{}'.format(type(self).__name__, schema_as_string) - # pieces = [title] - # if preview_cols: - # pieces.append('----') - # for i in range(min(self.num_columns, preview_cols)): - # pieces.append('{}: {}'.format( - # self.field(i).name, - # self.column(i).to_string(indent=0, skip_new_lines=True) - # )) - # if preview_cols < self.num_columns: - # pieces.append('...') - # return '\n'.join(pieces) - - # def __repr__(self): - # if self.table == NULL: - # raise ValueError("Table's internal pointer is NULL, do not use " - # "any methods or attributes on this object") - # return self.to_string(preview_cols=10) - cdef void init(self, const shared_ptr[CTable]& table): self.sp_table = table self.table = table.get()