/usr/local/lib/python3.6/site-packages/datasets/__pycache__
NameSizeModeActions
arrow_dataset.cpython-36.pyc1898500644editdlrm
arrow_reader.cpython-36.pyc224830644editdlrm
arrow_writer.cpython-36.pyc221100644editdlrm
builder.cpython-36.pyc527790644editdlrm
combine.cpython-36.pyc55080644editdlrm
config.cpython-36.pyc51810644editdlrm
dataset_dict.cpython-36.pyc833190644editdlrm
data_files.cpython-36.pyc301530644editdlrm
fingerprint.cpython-36.pyc189790644editdlrm
info.cpython-36.pyc173590644editdlrm
inspect.cpython-36.pyc185830644editdlrm
iterable_dataset.cpython-36.pyc629320644editdlrm
keyhash.cpython-36.pyc33410644editdlrm
load.cpython-36.pyc629220644editdlrm
metric.cpython-36.pyc232170644editdlrm
naming.cpython-36.pyc25710644editdlrm
search.cpython-36.pyc313390644editdlrm
splits.cpython-36.pyc225220644editdlrm
streaming.cpython-36.pyc41190644editdlrm
table.cpython-36.pyc796120644editdlrm
__init__.cpython-36.pyc22820644editdlrm
Edit: /usr/local/lib/python3.6/site-packages/datasets/__pycache__/table.cpython-36.pyc (79612B)
3 <%EgA@sddlZddlZddlZddlZddlmZddlmZddlm Z m Z m Z m Z m Z mZmZddlZddlZddlmZddlmZe rddlmZmZeeZd d Zeejd d d Z ej!ejdddZ"eejd ddZ#ejee$dddZ%e&dddZ'e e$e$e$dddZ(GdddZ)Gddde)ZGd d!d!eZ*Gd"d#d#e*Z+e ee,e&fZ-Gd$d%d%e*Z.ed&e*e e*e e e*Z/Gd'd(d(eZ0dLe ee$ed)d*d+Z1ee ed,d-d.Z2d/d0Z3e3dMej4ej5d2d3d4Z6e3dNej4d5d6d7d8Z7e3ej4d5d6d9d:Z8ejd;d<d=d>Z9ejej:d?d@dAZ;ejdBdCdDZeje ej4gdfdIdJdKZ?dS)ON)partial)groupby) TYPE_CHECKINGCallableListOptionalTupleTypeVarUnion)config) get_logger)Features FeatureTypecsfdd}|S)NcsBj|jdk r|jnd|_|jjdd|_tdr>j|_|S)Nz pyarrow.TableTable__annotations__)__doc__replacehasattrr)fn)arrow_table_method8/usr/local/lib/python3.6/site-packages/datasets/table.pywrappers  z1inject_arrow_table_documentation..wrapperr)rrr)rr inject_arrow_table_documentations r)filenamereturncCs"tj|}tjj|}|j}|S)N)paZ input_streamipc open_streamread_all)rZin_memory_stream opened_streampa_tablerrr _in_memory_arrow_table_from_file"s  r$)bufferrcCs"tj|}tjj|}|j}|S)N)rZ BufferReaderrr r!)r%streamr"tablerrr"_in_memory_arrow_table_from_buffer)s  r(cCs"tj|}tjj|}|j}|S)N)rZ memory_maprr r!)rZmemory_mapped_streamr"r#rrr$_memory_mapped_arrow_table_from_file0s  r))r'rrc Cs`t|dL}tj||jd}|j}x|D]}|j|q*W|jtdd|DSQRXdS)Nwb)sinkschemacss|] }|jVqdS)N)nbytes).0batchrrr >sz'_write_table_to_file..)openrZRecordBatchStreamWriterr, to_batchesZ write_batchclosesum)r'rr+writerbatchesr/rrr_write_table_to_file7s  r7)memocCsL|j}|j|}||t|<x*|jjD]\}}t||tj||q(W|S)z!deepcopy a regular class instance) __class____new__id__dict__itemssetattrcopydeepcopy)xr8clsresultkvrrr _deepcopyAs   rF)arrrArcCsdt|d}}x||kr|||ko6||knr||||||||||}|||ko||dknr|S|||kr|d|}}q||}}qWtd|dt|r|dndddS) ak Return the position i of a sorted array so that arr[i] <= x < arr[i+1] Args: arr (:obj:`List[int]`): non-empty sorted list of integers x (:obj:`int`): query Returns: `int`: the position i so that arr[i] <= x < arr[i+1] Raises: `IndexError`: if the array is empty or if the query is outside the array values rr zInvalid query 'z ' for size none.N)len IndexError)rGrAijrDrrr_interpolation_searchKs*($ rOc@sNeZdZejdddZeeee j fejdddZ d ejd d d Z dS) IndexedTableMixin)r'cCsD|j|_dd|jD|_tjdgdd|jDtjd|_dS)NcSsg|]}t|dkr|qS)r)rK)r.Z recordbatchrrr hsz.IndexedTableMixin.__init__..rcSsg|] }t|qSr)rK)r.brrrrQis)Zdtype)r,_schemar2_batchesnpZcumsumZint64_offsets)selfr'rrr__init__fszIndexedTableMixin.__init__)indicesrcsLt|stdtjj|ddd}tjjfddt||Dj dS)a' Create a pa.Table by gathering the records at the records at the specified indices. Should be faster than pa.concat_tables(table.fast_slice(int(i) % table.num_rows, 1) for i in indices) since NumPy can compute the binary searches in parallel, highly optimized C zIndices must be non-emptyright)Zsider cs,g|]$\}}j|j|j|dqS)r )rTslicerV)r.Z batch_idxrM)rWrrrQvsz1IndexedTableMixin.fast_gather..)r,) rK ValueErrorrUZ searchsortedrVrr from_batchesziprS)rWrYZ batch_indicesr)rWr fast_gatherks  zIndexedTableMixin.fast_gatherrN)rcCs |dkrtdn0||jdks0|dk rB|dkrBtjjg|jdSt|j|}|dksh|||jdkr|j|d}|dj||j||d<ndt|j||d}|j||d}|djd|||j||d <|dj||j||d<tjj||jdS) aO Slice the Table using interpolation search. The behavior is the same as :obj:`pyarrow.Table.slice` but it's significantly faster. Interpolation search is used to find the start and end indexes of the batches we want to keep. The batches to keep are then concatenated to form the sliced Table. rzOffset must be non-negativer N)r,rJrJrJrJ) rLrVrrr]rSrOrTr[)rWoffsetlengthrMr6rNrrr fast_slice|s  "zIndexedTableMixin.fast_slice)rN) __name__ __module__ __qualname__rrrXr rintrUZndarrayr_rbrrrrrPes rPcs~eZdZdZejdfdd ZedddZdd Z d d Z d d Z ddZ ddZ ddZddZddZddZddZddZeddZed d!Zed"d#Zed$d%Zed&d'Zed(d)Zed*d+Zd,d-Zd.d/Zd0d1Zd2d3Zd4d5Z d6d7Z!d8d9Z"d:d;Z#dd?Z%d@dAZ&dBdCZ'dDdEZ(dFdGZ)dHdIZ*dJdKZ+dLdMZ,e-e.ddNdOdPZ/Z0S)Qra Wraps a pyarrow Table by using composition. This is the base class for InMemoryTable, MemoryMappedTable and ConcatenationTable. It implements all the basic attributes/methods of the pyarrow Table class except the Table transforms: slice, filter, flatten, combine_chunks, cast, add_column, append_column, remove_column, set_column, rename_columns and drop. The implementation of these methods differs for the subclasses. )r'cstj|||_dS)N)superrXr')rWr')r9rrrXs zTable.__init__)r8cCs.|j|t|j<t|j|t|j<t||S)N)r'r;listrTrF)rWr8rrr __deepcopy__szTable.__deepcopy__c Csf|jjtjkrX|j}tjdddd,}|j}tjd|t ||dd|iSQRXn d|jiSdS) Nr*Fz.arrow)deletesuffixzQAttempting to pickle a table bigger than 4GiB. Writing it on the disk instead at )r'rpathr') r'r-r ZMAX_TABLE_NBYTES_FOR_PICKLINGtempfileNamedTemporaryFilenameloggerdebugr7)rWr'Ztmp_filerrrr __getstate__s  zTable.__getstate__cCs\d|krD|d}tjd|t|}tjd|tj|n|d}tj||dS)Nrlz(Unpickling a big table from the disk at z!Removing temporary table file at r')rprqr$osremoverrX)rWstaterr'rrr __setstate__s zTable.__setstate__cOs|jj||S)a 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)). Args: full (:obj:`bool`, defaults to :obj:`False`): If True, run expensive checks, otherwise cheap checks only. Raises: pa.lib.ArrowInvalid: if validation fails )r'validate)rWargskwargsrrrrwszTable.validatecOs.tdd|D}dd|D}|jj||S)ab Check if contents of two tables are equal. Args: other (:class:`datasets.table.Table`): Table to compare against. check_metadata (:obj:`bool`, defaults to :obj:`False`): Whether schema metadata equality should be checked as well. Returns: :obj:`bool` css"|]}t|tr|jn|VqdS)N) isinstancerr')r.argrrrr0szTable.equals..cSs&i|]\}}t|tr|jn||qSr)rzrr')r.rDrErrr sz Table.equals..)tupler'equals)rWrxryrrrr~s z Table.equalscOs|jj||S)ar Convert Table to list of (contiguous) RecordBatch objects. Args: max_chunksize (:obj:`int`, defaults to `None`): Maximum size for RecordBatch chunks. Individual chunks may be smaller depending on the chunk layout of individual columns. Returns: :obj:`List[pyarrow.RecordBatch]`: )r'r2)rWrxryrrrr2s zTable.to_batchescOs|jj||S)zg Convert the Table to a dict or OrderedDict. Returns: :obj:`dict` )r' to_pydict)rWrxryrrrrszTable.to_pydictcOs|jj||S)a) Convert to a pandas-compatible NumPy array or DataFrame, as appropriate Args: memory_pool (:obj:`MemoryPool`, defaults to :obj:`None`): Arrow MemoryPool to use for allocations. Uses the default memory pool is not passed. strings_to_categorical (:obj:`bool`, defaults to :obj:`False`): Encode string (UTF8) and binary types to pandas.Categorical. categories (:obj:`list`, defaults to :obj:`empty`): List of fields that should be returned as pandas.Categorical. Only applies to table-like data structures. zero_copy_only (:obj:`bool`, defaults to :obj:`False`): Raise an ArrowException if this function call would require copying the underlying data. integer_object_nulls (:obj:`bool`, defaults to :obj:`False`): Cast integers with nulls to objects date_as_object (:obj:`bool`, defaults to :obj:`True`): Cast dates to objects. If False, convert to datetime64[ns] dtype. timestamp_as_object (:obj:`bool`, defaults to :obj:`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_threads (:obj:`bool`, defaults to :obj:`True`): Whether to parallelize the conversion using multiple threads. deduplicate_objects (:obj:`bool`, defaults to :obj:`False`): Do not create multiple copies Python objects when created, to save on memory use. Conversion will be slower. ignore_metadata (:obj:`bool`, defaults to :obj:`False`): If True, do not use the 'pandas' metadata to reconstruct the DataFrame index, if present safe (:obj:`bool`, defaults to :obj:`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_blocks (:obj:`bool`, defaults to :obj:`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_destruct (:obj:`bool`, defaults to :obj:`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. types_mapper (:obj:`function`, defaults to :obj:`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: :obj:`pandas.Series` or :obj:`pandas.DataFrame`: :obj:`pandas.Series` or :obj:`pandas.DataFrame` depending on type of object )r' to_pandas)rWrxryrrrrs     rc@seZdZdZdS) TableBlockz TableBlock is the allowed class inside a ConcanetationTable. Only MemoryMappedTable and InMemoryTable are TableBlock. This is because we don't want a ConcanetationTable made out of other ConcanetationTables. N)rcrdrerrrrrrmsrc@seZdZdZeedddZeejdddZ edd Z ed d Z ed d Z eddZ d*ddZddZddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)ZdS)+ InMemoryTableaW The table is said in-memory when it is loaded into the user's RAM. Pickling it does copy all the data using memory. Its implementation is simple and uses the underlying pyarrow Table methods directly. This is different from the MemoryMapped table, for which pickling doesn't copy all the data in memory. For a MemoryMapped, unpickling instead reloads the table from the disk. InMemoryTable must be used when data fit in memory, while MemoryMapped are reserved for data bigger than memory or when you want the memory footprint of your application to stay low. )rcCst|}||S)N)r$)rBrr'rrr from_fileszInMemoryTable.from_file)r%cCst|}||S)N)r()rBr%r'rrr from_bufferszInMemoryTable.from_buffercOs|tjj||S)an 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. Args: df (:obj:`pandas.DataFrame`): schema (:obj:`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_index (:obj:`bool`, 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. nthreads (:obj:`int`, defaults to :obj:`None` (may use up to system CPU count threads)) If greater than 1, convert columns to Arrow in parallel using indicated number of threads columns (:obj:`List[str]`, optional): List of column to be converted. If None, use all columns. safe (:obj:`bool`, defaults to :obj:`True`): Check for overflows or other unsafe conversions Returns: :class:`datasets.table.Table`: Examples: ```python >>> import pandas as pd >>> import pyarrow as pa >>> df = pd.DataFrame({ ... 'int': [1, 2], ... 'str': ['a', 'b'] ... }) >>> pa.Table.from_pandas(df) ``` )rr from_pandas)rBrxryrrrrs8zInMemoryTable.from_pandascOs|tjj||S)a Construct a Table from Arrow arrays Args: arrays (:obj:`List[Union[pyarrow.Array, pyarrow.ChunkedArray]]`): Equal-length arrays that should form the table. names (:obj:`List[str]`, optional): Names for the table columns. If not passed, schema must be passed schema (:obj:`Schema`, defaults to :obj:`None`): Schema for the created table. If not passed, names must be passed metadata (:obj:`Union[dict, Mapping]`, default None): Optional metadata for the schema (if inferred). Returns: :class:`datasets.table.Table`: )rr from_arrays)rBrxryrrrrszInMemoryTable.from_arrayscOs|tjj||S)a Construct a Table from Arrow arrays or columns Args: mapping (:obj:`Union[dict, Mapping]`): A mapping of strings to Arrays or Python lists. schema (:obj:`Schema`, defaults to :obj:`None`): If not passed, will be inferred from the Mapping values metadata (:obj:`Union[dict, Mapping]`, default None): Optional metadata for the schema (if inferred). Returns: :class:`datasets.table.Table`: )rr from_pydict)rBrxryrrrrszInMemoryTable.from_pydictcOs|tjj||S)a Construct a Table from a sequence or iterator of Arrow RecordBatches. Args: batches (:obj:`Union[Sequence[pyarrow.RecordBatch], Iterator[pyarrow.RecordBatch]]`): Sequence of RecordBatch to be converted, all schemas must be equal. schema (:obj:`Schema`, defaults to :obj:`None`): If not passed, will be inferred from the first RecordBatch. Returns: :class:`datasets.table.Table`: )rrr])rBrxryrrrr]szInMemoryTable.from_batchesrNcCst|j||dS)a Compute zero-copy slice of this Table Args: offset (:obj:`int`, defaults to :obj:`0`): Offset from start of table to slice length (:obj:`int`, defaults to :obj:`None`): Length of slice (default is until end of table starting from offset) Returns: :class:`datasets.table.Table`: )r`ra)rrb)rWr`rarrrr[szInMemoryTable.slicecOst|jj||S)zY Select records from a Table. See pyarrow.compute.filter for full usage. )rr'r)rWrxryrrrrszInMemoryTable.filtercOstt|jf||S)a Flatten this Table. Each column with a struct type is flattened into one column per struct field. Other columns are left unchanged. Args: memory_pool (:obj:`MemoryPool`, defaults to :obj:`None`): For memory allocations, if required, otherwise use default pool Returns: :class:`datasets.table.Table`: )r table_flattenr')rWrxryrrrrs zInMemoryTable.flattencOst|jj||S)a 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. Args: memory_pool (:obj:`MemoryPool`, defaults to :obj:`None`): For memory allocations, if required, otherwise use default pool Returns: :class:`datasets.table.Table`: )rr'r)rWrxryrrrr%szInMemoryTable.combine_chunkscOstt|jf||S)aq Cast table values to another schema Args: target_schema (:obj:`Schema`): Schema to cast to, the names and order of fields must match safe (:obj:`bool`, defaults to :obj:`True`): Check for overflows or other unsafe conversions Returns: :class:`datasets.table.Table`: )r table_castr')rWrxryrrrr5s zInMemoryTable.castcOst|jj||S)aa EXPERIMENTAL: 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 Args: metadata (:obj:`dict`, defaults to :obj:`None`): Returns: :class:`datasets.table.Table`: shallow_copy )rr'r)rWrxryrrrrDs z%InMemoryTable.replace_schema_metadatacOst|jj||S)a] Add column to Table at position. A new table is returned with the column added, the original table object is left unchanged. Args: i (:obj:`int`): Index to place the column at. field_ (:obj:`Union[str, pyarrow.Field]`): If a string is passed then the type is deduced from the column data. column (:obj:`Union[pyarrow.Array, List[pyarrow.Array]]`): Column data. Returns: :class:`datasets.table.Table`: New table with the passed column added. )rr'r)rWrxryrrrrRszInMemoryTable.add_columncOst|jj||S)a Append column at end of columns. Args: field_ (:obj:`Union[str, pyarrow.Field]`): If a string is passed then the type is deduced from the column data. column (:obj:`Union[pyarrow.Array, List[pyarrow.Array]]`): Column data. Returns: :class:`datasets.table.Table`: New table with the passed column added. )rr'r)rWrxryrrrrgszInMemoryTable.append_columncOst|jj||S)a Create new Table with the indicated column removed. Args: i (:obj:`int`): Index of column to remove. Returns: :class:`datasets.table.Table`: New table without the column. )rr'r)rWrxryrrrrxs zInMemoryTable.remove_columncOst|jj||S)a Replace column in Table at position. Args: i (:obj:`int`): Index to place the column at. field_ (:obj:`Union[str, pyarrow.Field]`): If a string is passed then the type is deduced from the column data. column (:obj:`Union[pyarrow.Array, List[pyarrow.Array]]`): Column data. Returns: :class:`datasets.table.Table`: New table with the passed column set. )rr'r)rWrxryrrrrszInMemoryTable.set_columncOst|jj||S)zJ Create new table with columns renamed to provided names. )rr'r)rWrxryrrrrszInMemoryTable.rename_columnscOst|jj||S)a Drop one or more columns and return a new table. Args: columns (:obj:`List[str]`): List of field names referencing existing columns. Raises: KeyError : if any of the passed columns name are not existing. Returns: :class:`datasets.table.Table`: New table without the columns. )rr'r)rWrxryrrrrszInMemoryTable.drop)rN)rcrdrer classmethodstrrrBufferrrrrr]r[rrrrrrrrrrrrrrrrws*  :    rcseZdZdZd,ejeeee dfdd Z e d-edddZ d d Z d d Zed.ejeee ejd ddZe ee dddZd/ddZddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+ZZS)0MemoryMappedTableaN The table is said memory mapped when it doesn't use the user's RAM but loads the data from the disk instead. Pickling it doesn't copy the data into memory. Instead, only the path to the memory mapped arrow file is pickled, as well as the list of transforms to "replay" when reloading the table from the disk. Its implementation requires to store an history of all the transforms that were applied to the underlying pyarrow Table, so that they can be "replayed" when reloading the Table from the disk. This is different from the InMemoryTable table, for which pickling does copy all the data in memory. InMemoryTable must be used when data fit in memory, while MemoryMapped are reserved for data bigger than memory or when you want the memory footprint of your application to stay low. N)r'rlreplayscs(tj|||_|dk r|ng|_dS)N)rgrXrlr)rWr'rlr)r9rrrXs zMemoryMappedTable.__init__)rcCs t|}|j||}||||S)N)r)_apply_replays)rBrrr'rrrrs zMemoryMappedTable.from_filecCs|j|jdS)N)rlr)rlr)rWrrrrrszMemoryMappedTable.__getstate__cCs:|d}|d}t|}|j||}tj||||ddS)Nrlr)rlr)r)rrrX)rWrurlrr'rrrrvs  zMemoryMappedTable.__setstate__)r'rrcCsd|dk r`xV|D]N\}}}|dkr2t|f||}q|dkrLt|f||}qt||||}qW|S)Nrr)rrgetattr)r'rrorxryrrrrsz MemoryMappedTable._apply_replays)replayrcCstj|j}|j||S)N)r?r@rappend)rWrrrrr_append_replays  z MemoryMappedTable._append_replayrcCs0d||fif}|j|}t|j||d|j|S)a Compute zero-copy slice of this Table Args: offset (:obj:`int`, defaults to :obj:`0`): Offset from start of table to slice length (:obj:`int`, defaults to :obj:`None`): Length of slice (default is until end of table starting from offset) Returns: :class:`datasets.table.Table`: r[)r`ra)rrrbrl)rWr`rarrrrrr[s zMemoryMappedTable.slicecOs8dtj|tj|f}|j|}t|jj|||j|S)zY Select records from a Table. See pyarrow.compute.filter for full usage. r)r?r@rrr'rrl)rWrxryrrrrrrs zMemoryMappedTable.filtercOs<dtj|tj|f}|j|}tt|jf|||j|S)a Flatten this Table. Each column with a struct type is flattened into one column per struct field. Other columns are left unchanged. Args: memory_pool (:obj:`MemoryPool`, defaults to :obj:`None`): For memory allocations, if required, otherwise use default pool Returns: :class:`datasets.table.Table`: r)r?r@rrrr'rl)rWrxryrrrrrr s  zMemoryMappedTable.flattencOs8dtj|tj|f}|j|}t|jj|||j|S)a 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. Args: memory_pool (:obj:`MemoryPool`, defaults to :obj:`None`): For memory allocations, if required, otherwise use default pool Returns: :class:`datasets.table.Table`: r)r?r@rrr'rrl)rWrxryrrrrrrs z MemoryMappedTable.combine_chunkscOs<dtj|tj|f}|j|}tt|jf|||j|S)aq Cast table values to another schema Args: target_schema (:obj:`Schema`): Schema to cast to, the names and order of fields must match safe (:obj:`bool`, defaults to :obj:`True`): Check for overflows or other unsafe conversions Returns: :class:`datasets.table.Table`: r)r?r@rrrr'rl)rWrxryrrrrrr-s  zMemoryMappedTable.castcOs8dtj|tj|f}|j|}t|jj|||j|S)aa EXPERIMENTAL: 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 Args: metadata (:obj:`dict`, defaults to :obj:`None`): Returns: :class:`datasets.table.Table`: shallow_copy r)r?r@rrr'rrl)rWrxryrrrrrr>s  z)MemoryMappedTable.replace_schema_metadatacOs8dtj|tj|f}|j|}t|jj|||j|S)a] Add column to Table at position. A new table is returned with the column added, the original table object is left unchanged. Args: i (:obj:`int`): Index to place the column at. field_ (:obj:`Union[str, pyarrow.Field]`): If a string is passed then the type is deduced from the column data. column (:obj:`Union[pyarrow.Array, List[pyarrow.Array]]`): Column data. Returns: :class:`datasets.table.Table`: New table with the passed column added. r)r?r@rrr'rrl)rWrxryrrrrrrNs zMemoryMappedTable.add_columncOs8dtj|tj|f}|j|}t|jj|||j|S)a Append column at end of columns. Args: field_ (:obj:`Union[str, pyarrow.Field]`): If a string is passed then the type is deduced from the column data. column (:obj:`Union[pyarrow.Array, List[pyarrow.Array]]`): Column data. Returns: :class:`datasets.table.Table`: New table with the passed column added. r)r?r@rrr'rrl)rWrxryrrrrrres zMemoryMappedTable.append_columncOs8dtj|tj|f}|j|}t|jj|||j|S)a Create new Table with the indicated column removed. Args: i (:obj:`int`): Index of column to remove. Returns: :class:`datasets.table.Table`: New table without the column. r)r?r@rrr'rrl)rWrxryrrrrrrxs  zMemoryMappedTable.remove_columncOs8dtj|tj|f}|j|}t|jj|||j|S)a Replace column in Table at position. Args: i (:obj:`int`): Index to place the column at. field_ (:obj:`Union[str, pyarrow.Field]`): If a string is passed then the type is deduced from the column data. column (:obj:`Union[pyarrow.Array, List[pyarrow.Array]]`): Column data. Returns: :class:`datasets.table.Table`: New table with the passed column set. r)r?r@rrr'rrl)rWrxryrrrrrrs zMemoryMappedTable.set_columncOs8dtj|tj|f}|j|}t|jj|||j|S)zJ Create new table with columns renamed to provided names. r)r?r@rrr'rrl)rWrxryrrrrrrs z MemoryMappedTable.rename_columnscOs8dtj|tj|f}|j|}t|jj|||j|S)a Drop one or more columns and return a new table. Args: columns (:obj:`List[str]`): List of field names referencing existing columns. Raises: KeyError : if any of the passed columns name are not existing. Returns: :class:`datasets.table.Table`: New table without the columns. r)r?r@rrr'rrl)rWrxryrrrrrrs zMemoryMappedTable.drop)N)N)N)rN)rcrdrerrrrrrReplayrXrrrrrv staticmethodrrr[rrrrrrrrrrrrrr)r9rrs*""  rTableBlockContainercs`eZdZdZejeeedfdd ZddZ ddZ e d4ee eejfe ejd d d Zeeeeejd ddZed5eee ed ddZeeed ddZeedd ddZed6ee ejefe ddddZeddZd7ddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Z d,d-Z!d.d/Z"d0d1Z#d2d3Z$Z%S)8ConcatenationTableao The table comes from the concatenation of several tables called blocks. It enables concatenation on both axis 0 (append rows) and axis 1 (append columns). The underlying tables are called "blocks" and can be either InMemoryTable or MemoryMappedTable objects. This allows to combine tables that come from memory or that are memory mapped. When a ConcatenationTable is pickled, then each block is pickled: - the InMemoryTable objects are pickled by copying all the data in memory; - the MemoryMappedTable objects are pickled without copying the data into memory. Instead, only the path to the memory mapped arrow file is pickled, as well as the list of transforms to "replays" when reloading the table from the disk. Its implementation requires to store each block separately. The ``blocks`` attributes stores a list of list of blocks. The first axis concatenates the tables along the axis 0 (it appends rows), while the second axis concatenates tables along the axis 1 (it appends columns). If some columns are missing when concatenating on axis 0, they are filled with null values. This is done using `pyarrow.concat_tables(tables, promote=True)`. You can access the fully combined table by accessing the ConcatenationTable.table attribute, and the blocks by accessing the ConcatenationTable.blocks attribute. )r'blockscsLtj|||_x4|D],}x&|D]}t|ts"td|dq"WqWdS)Nz_The blocks of a ConcatenationTable must be InMemoryTable or MemoryMappedTable objects, but got rI)rgrXrrzr TypeError)rWr'r subtablessubtable)r9rrrXs    zConcatenationTable.__init__cCs d|jiS)Nr)r)rWrrrrrszConcatenationTable.__getstate__cCs&|d}|j|}tj|||ddS)Nr)r)*_concat_blocks_horizontally_and_verticallyrrX)rWrurr'rrrrvs zConcatenationTable.__setstate__r)raxisrcCsdd|D}|dkr$tj|ddS|dkr|xJt|D]>\}}|dkrL|}q6x&t|j|jD]\}}|j||}q\Wq6W|StddS)NcSs g|]}t|dr|jn|qS)r')rr')r.r'rrrrQsz5ConcatenationTable._concat_blocks..rT)Zpromoter z'axis' must be either 0 or 1)r concat_tables enumerater^rrrr\)rrZ pa_tablesrMr'r#rocolrrr_concat_blockssz!ConcatenationTable._concat_blocks)rrcCsFg}x2t|D]&\}}|sq|j|dd}|j|qW|j|ddS)Nr )rr)rrr)rBrZpa_tables_to_concat_verticallyrMtablesZ"pa_table_horizontally_concatenatedrrrrsz=ConcatenationTable._concat_blocks_horizontally_and_verticallyNcs|dk rTg}xt|dddD]0\}}|rBtjt||dg}|t|7}qWn<fdd|D}tdd|Drjd d|Dd d}|S) NcSs t|tS)N)rzr)rArrrsz2ConcatenationTable._merge_blocks..)key)rcsg|]}j|ddqS)r )r) _merge_blocks)r. row_block)rBrrrQsz4ConcatenationTable._merge_blocks..css|]}t|dkVqdS)r N)rK)r.rrrrr0sz3ConcatenationTable._merge_blocks..cSsg|]}|D]}|q qSrr)r.rblockrrrrQsr)rrrrhallr)rBrrZ merged_blocksZ is_in_memoryZ block_groupr)rBrr sz ConcatenationTable._merge_blockscCs8t|tr|St|dtr*|j|ddS|j|SdS)Nr)r)rzrr)rBrrrr_consolidate_blockss  z&ConcatenationTable._consolidate_blockscCst|j|}t|tr(|}||j|ggSt|dtr\|j|dd}dd|D}|||S|j|}|||SdS)Nr)rcSsg|] }|gqSrr)r.trrrrQ+sz2ConcatenationTable.from_blocks..)rrzrr'rr)rBrr'rrr from_blocks#s    zConcatenationTable.from_blocks)rrrcspdd}ddd ttttdfdd }||d}x*|d d D]}||}||||d }qHW|j|S) aCreate ConcatenationTable from list of tables. Args: tables (list of :class:`Table` or list of :obj:`pyarrow.Table`): List of tables. axis: (``{0, 1}``, defaults to :obj:`0`, meaning over rows): Axis to concatenate over, where ``0`` means over rows (vertically) and ``1`` means over columns (horizontally). *New in version 1.6.0* cSs:t|tjrt|ggSt|tr.tj|jS|ggSdS)N)rzrrrrr?r@r)r'rrr to_blocks>s     z1ConcatenationTable.from_tables..to_blockscsHg}d}x,|D]$}|dj}|j||f||7}qWfdd|DS)Nrcs"g|]fdddDqS)cs"g|]}|jdddqS)rr )r`ra)r[)r.r)splitrrrQNszRConcatenationTable.from_tables.._split_like...rr)r.)blocks_to_split)rrrQNszGConcatenationTable.from_tables.._split_like..)rr)rZ blocks_likesplitsr`Z block_rowrar)rr _split_likeFs   z3ConcatenationTable.from_tables.._split_liker)rrcs|dkr|j|nr|dkrt|dkr@t|dkr@||}n"t|dkrbt|dkrb||}x"t|D]\}}||j|qlW|S)Nrr )extendrKr)rCrrrMZ row_blocks)rrr_extend_blocksQs   z6ConcatenationTable.from_tables.._extend_blocksr N)r)r)rrrfr)rBrrrrrr'Z table_blocksr)rr from_tables1s   zConcatenationTable.from_tablesccs6d}x,|jD]"}t|d}||fV||7}q WdS)Nr)rrK)rWr`rrarrr_slicesds    zConcatenationTable._slicescs|jjd}dk rn|jg}x|jD]}t|d}dkrNPq2|kr`|q2|kr|jfdd|D|dq2|jfdd|Dd\q2Wt||S)a Compute zero-copy slice of this Table Args: offset (:obj:`int`, defaults to :obj:`0`): Offset from start of table to slice length (:obj:`int`, defaults to :obj:`None`): Length of slice (default is until end of table starting from offset) Returns: :class:`datasets.table.Table`: )raNrcsg|]}|jqSr)r[)r.r)r`rrrQsz,ConcatenationTable.slice..csg|]}|jqSr)r[)r.r)rar`rrrQs)rr)r'r[rrrKrr)rWr`rar'rrZn_rowsr)rar`rr[ls     zConcatenationTable.slicec sj|jj|f}g}xFt|j|jD]4\\}}}|j|||jfdd|Dq(Wt||S)zY Select records from a Table. See pyarrow.compute.filter for full usage. csg|]}|jfqSr)r)r.r)rxrysubmaskrrrQsz-ConcatenationTable.filter..)r'rr^rrr[rr) rWmaskrxryr'rr`rarr)rxryrrrs   zConcatenationTable.filtercsJt|jf}g}x(|jD]}|jfdd|DqWt||S)a Flatten this Table. Each column with a struct type is flattened into one column per struct field. Other columns are left unchanged. Args: memory_pool (:obj:`MemoryPool`, defaults to :obj:`None`): For memory allocations, if required, otherwise use default pool Returns: :class:`datasets.table.Table`: csg|]}|jqSr)r)r.r)rxryrrrQsz.ConcatenationTable.flatten..)rr'rrr)rWrxryr'rrr)rxryrrs  zConcatenationTable.flattencsF|jj}g}x(|jD]}|jfdd|DqWt||S)a 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. Args: memory_pool (:obj:`MemoryPool`, defaults to :obj:`None`): For memory allocations, if required, otherwise use default pool Returns: :class:`datasets.table.Table`: csg|]}|jqSr)r)r.r)rxryrrrQsz5ConcatenationTable.combine_chunks..)r'rrrr)rWrxryr'rrr)rxryrrs  z!ConcatenationTable.combine_chunksc sddlm}t|j|f||}|j|g}x|jD]}g}t|} xz|D]r} g} x4| jD]*| j| j t fddt | Dq\W|fdd| D} | j } |j| j | f||qLW|j|q6Wt||S)aq Cast table values to another schema Args: target_schema (:obj:`Schema`): Schema to cast to, the names and order of fields must match safe (:obj:`bool`, defaults to :obj:`True`): Check for overflows or other unsafe conversions Returns: :class:`datasets.table.Table`: r )rc3s |]\}}|jkr|VqdS)N)ro)r.rMr)rorrr0sz*ConcatenationTable.cast..csi|]}|j|jqSr)ro)r.subfield)target_featuresrrr|sz+ConcatenationTable.cast..)featuresrrr'from_arrow_schemarrhrrpopnextr arrow_schemarr)rWZ target_schemarxryrr'rrZ new_tablesfieldsrZ subfieldsZ subfeaturesZ subschemar)rorrrs     *zConcatenationTable.castcsH|jj}g}x(|jD]}|jfdd|DqWt||jS)aa EXPERIMENTAL: 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 Args: metadata (:obj:`dict`, defaults to :obj:`None`): Returns: :class:`datasets.table.Table`: shallow_copy csg|]}|jqSr)r)r.r)rxryrrrQsz>ConcatenationTable.replace_schema_metadata..)r'rrrr)rWrxryr'rrr)rxryrrs  z*ConcatenationTable.replace_schema_metadatacOs tdS)a] Add column to Table at position. A new table is returned with the column added, the original table object is left unchanged. Args: i (:obj:`int`): Index to place the column at. field_ (:obj:`Union[str, pyarrow.Field]`): If a string is passed then the type is deduced from the column data. column (:obj:`Union[pyarrow.Array, List[pyarrow.Array]]`): Column data. Returns: :class:`datasets.table.Table`: New table with the passed column added. N)r)rWrxryrrrrszConcatenationTable.add_columncOs tdS)a Append column at end of columns. Args: field_ (:obj:`Union[str, pyarrow.Field]`): If a string is passed then the type is deduced from the column data. column (:obj:`Union[pyarrow.Array, List[pyarrow.Array]]`): Column data. Returns: :class:`datasets.table.Table`: New table with the passed column added. N)r)rWrxryrrrrsz ConcatenationTable.append_columncsZ|jj|f}|jj|g}x*|jD] }|jfdd|Dq,Wt||S)a Create new Table with the indicated column removed. Args: i (:obj:`int`): Index of column to remove. Returns: :class:`datasets.table.Table`: New table without the column. cs4g|],}|jkr,|j|jjfn|qSr)rrindex)r.r)rxryrorrrQ%sz4ConcatenationTable.remove_column..)r'rrrrr)rWrMrxryr'rrr)rxryrorrs   z ConcatenationTable.remove_columncOs tdS)a Replace column in Table at position. Args: i (:obj:`int`): Index to place the column at. field_ (:obj:`Union[str, pyarrow.Field]`): If a string is passed then the type is deduced from the column data. column (:obj:`Union[pyarrow.Array, List[pyarrow.Array]]`): Column data. Returns: :class:`datasets.table.Table`: New table with the passed column set. N)r)rWrxryrrrr+szConcatenationTable.set_columncs`|jjf}tt|jjg}x*|jD] }|jfdd|Dq2Wt||S)zJ Create new table with columns renamed to provided names. cs.g|]&}|jfdd|jDfqS)csg|] }|qSrr)r.ro)namesrrrQGsz@ConcatenationTable.rename_columns...)rr)r.r)rxryrrrrQGsz5ConcatenationTable.rename_columns..)r'rrr^rrrr)rWrrxryr'rrr)rxryrrr>s z!ConcatenationTable.rename_columnscsF|jj}g}x*|jD] }|jfdd|DqWt||S)a Drop one or more columns and return a new table. Args: columns (:obj:`List[str]`): List of field names referencing existing columns. Raises: KeyError : if any of the passed columns name are not existing. Returns: :class:`datasets.table.Table`: New table without the columns. cs,g|]$jfddDfqS)csg|]}|jkr|qSr)r)r.c)rrrrQ]sz6ConcatenationTable.drop...)r)r.)rxrry)rrrQ]sz+ConcatenationTable.drop..)r'rrrr)rWrrxryr'rrr)rxrryrrKs    zConcatenationTable.drop)r)N)r)rN)&rcrdrerrrrrrXrrrvrr rfrrrrrrrrrrrr[rrrrrrrrrrrrrr)r9rrs: &  $2    r)rrrcCs*t|}t|dkr|dStj||dS)aY Concatenate tables. Args: tables (list of :class:`Table`): List of tables to be concatenated. axis (``{0, 1}``, defaults to :obj:`0`, meaning over rows): Axis to concatenate over, where ``0`` means over rows (vertically) and ``1`` means over columns (horizontally). *New in version 1.6.0* Returns: :class:`datasets.table.Table`: If the number of input tables is > 1, then the returned table is a :obj:`datasets.table.ConcatenationTable`. Otherwise if there's only one table, it is returned as is. r r)r)rhrKrr)rrrrrras r)r'rcCsVt|trt|tjr*tjfdd|jDS|fSdS)Ncsg|]}|fqSrr)r.chunk)rxfuncryrrrQsz=_wrap_for_chunked_arrays..wrapper..)rzr ChunkedArrayZ chunked_arraychunks)arrayrxry)r)rxryrrs z)_wrap_for_chunked_arrays..wrapperr)rrr)rr_wrap_for_chunked_arrayss rT)rpa_typecstt|dttjrjt|tjr4|jSj|krBStj j jrtj j |rt dd|Dt ddjDkrfdd|D}tj j |t|jdSntj jjrRtj j|r|jttjkrNtjj j|j|jSnFtj j|r~jdkr4tjd|d tjj jj|jSn,tj jjrtj j|rtjj j|j|jStj j|r~tjttd tj}jdkrtjd|d tjj |j|jSn| r>tj j|r>tj j js"tj j!jr>t"d jd |d |tj j|rttj jj rtt"d jd |j#|St"djd|dS)a-Improved version of pa.Array.cast It supports casting pa.StructArray objects to re-order the fields. It also let you control certain aspects of the casting, e.g. whether to disable numbers (floats or ints) to strings. Args: array (pa.Array): PyArrow array to cast pa_type (pa.DataType): target PyArrow type allow_number_to_str (bool, defaults to :obj:`True`): Whether to allow casting numbers to strings. Defaults to True. Raises: pa.ArrowInvalidError: if the arrow data casting fails TypeError: if the target type is not supported according, e.g. - if a field is missing = if casting from numbers to strings and allow_number_to_str is False Returns: :obj:`List[pyarrow.Array]`: the casted array )allow_number_to_strcss|] }|jVqdS)N)ro)r.rrrrr0szarray_cast..cs g|]}j|j|jqSr)rrotype)r.r)_crrrrQszarray_cast..)rrrzBNone values are converted to empty lists when converting array to z. More info: https://github.com/huggingface/datasets/issues/3676. This will raise an error in a future major version of `datasets`r zCouldn't cast array of type z to z% since allow_number_to_str is set to zCouldn't cast array of type z to N)$r array_castrzrExtensionArraystorageZ ExtensionTypeZ wrap_arrayrtypes is_structr StructArrayrrhis_nullis_listis_fixed_size_listZ list_sizerKvaluesFixedSizeListArrayZ value_type null_countwarningswarn ListArrayoffsetsrrint32 is_stringZ is_floating is_integerrr)rrrarrays offsets_arrr)rrrrsV      &        rr)rfeaturecsLddlmm}tt|dttjr.jt drBj Stj j j rtrtjtrfddjjDttrtddj Dtkr؇fd d jD}tjj|tjd Sntj jj rttrLjd }|j jj krSjd kr:tjd dtjjj|SntrjdkrjttjkrtjjjjjSnZjj}|j jj krSjd krtjd dtjjjjjSntj j j rttrLjd kr0tjd dtjjjjd StrjdkrjttjkrtjjjjjSnRtj!t"tdtj#}jd krtjd dtjj|jjStj jj rt$||dStttt%fs2t$|dSt&dj ddS)a9Cast an array to the arrow type that corresponds to the requested feature type. For custom features like Audio or Image, it takes into account the "cast_storage" methods they defined to enable casting from other arrow types. Args: array (pa.Array): the PyArrow array to cast feature (FeatureType): the target feature type allow_number_to_str (bool, defaults to :obj:`True`): Whether to allow casting numbers to strings. Defaults to True. Raises: pa.ArrowInvalidError: if the arrow data casting fails TypeError: if the target type is not supported according, e.g. - if a field is missing = if casting from numbers to strings and allow_number_to_str is False Returns: array (:obj:`pyarrow.Array`): the casted array r )Sequenceget_nested_type)r cast_storagecs i|]\}}|jd|qS))ra)ra)r.ro subfeature)rrrrr|sz)cast_array_to_feature..css|] }|jVqdS)N)ro)r.rrrrr0 sz(cast_array_to_feature..cs g|]\}}j||qSr)r)r.ror)rrrrrQ sz)cast_array_to_feature..)rrrzBNone values are converted to empty lists when converting array to z. More info: https://github.com/huggingface/datasets/issues/3676. This will raise an error in a future major version of `datasets`zCouldn't cast array of type z to NrJrJ)'features.featuresrrrcast_array_to_featurerzrrrrrrrrrrr=rrrrhrrrrrrrrrarKrrrrrrr}r)rrrrr casted_valuesrr)rrrrrr sj     &          r csddlmtttjr"jtdr6jStj j j rtrttj t rtfddj jDtt rfddjD}tjj|tjdSntj jj rttrjd krtjd d tjjjjd StrjdkrVjttjkrtjjjj jSnZjj }|j jj krxSjd krtjd d tjjjjj Sntj jj rttrjd krtjd d tjjjjd StrjdkrVjttjkrtjjjj jSnRtjttdtj }jd krtjd d tjj|jj Stt tt!fsSt"d j d dS)a&Embed data into an arrays's storage. For custom features like Audio or Image, it takes into account the "embed_storage" methods they defined to enable embedding external data (e.g. an image file) into an other arrow types. Args: array (pa.Array): the PyArrow array in which to embed data feature (FeatureType): array features Raises: TypeError: if the target type is not supported according, e.g. - if a field is missing Returns: array (:obj:`pyarrow.Array`): the casted array r )r embed_storagecs i|]\}}|jd|qS))ra)ra)r.ror)rrrrr|^sz'embed_array_storage..cs g|]\}}j||qSr)r)r.ror)_errrrQbsz'embed_array_storage..)rrrzKNone values are converted to empty lists when embedding array storage with z. More info: https://github.com/huggingface/datasets/issues/3676. This will raise an error in a future major version of `datasets`zCouldn't embed array of type z with NrJrJ)#rrembed_array_storagerzrrrrr rrrrrr=rrrhrrrrrrrrrarKrrrrrr}r)rrrr rr)rr rrrr As`                r r)r'rcsRtjt|kr*tdjd|dfdd|jD}tjj||jdS)a Cast a table to the arrow schema that corresponds to the requested features. Args: table (:obj:`pyarrow.Table`): PyArrow table to cast features (Features): target features. Returns: table (:obj:`pyarrow.Table`): the casted table zCouldn't cast z to z! because column names don't matchcsg|]\}}t||qSr)r )r.ror)r'rrrQsz*cast_table_to_features..)r,) sortedrr\r,r=rrrr)r'rrr)r'rcast_table_to_featuress r)r'r,csfddlm}|j|}tjt|kr@tdjd|dfdd|jD}tj j ||dS) aCast a table to the arrow schema. Different from `cast_table_to_features`, this method can preserve nullability. Args: table (pa.Table): PyArrow table to cast features (Features): target features. Returns: pa.Table: the casted table r )rzCouldn't cast z to z! because column names don't matchcsg|]\}}t||qSr)r )r.ror)r'rrrQsz(cast_table_to_schema..)r,) rrrrrr\r,r=rrr)r'r,rrrr)r'rcast_table_to_schemas  r)r'csFddlm}m|jj}fdd|jD}tjj||j dS)zEmbed external data into a table's storage. Args: table (:obj:`pyarrow.Table`): PyArrow table in which to embed data Returns: table (:obj:`pyarrow.Table`): the table with embedded data r )rrequire_storage_embedcs.g|]&\}}|r"t||n|qSr)r )r.ror)rr'rrrQsz'embed_table_storage..)r,) rrrrr,r=rrrr)r'rrrr)rr'rembed_table_storages    rcCs6|j|krt||S|jj|jkr.|j|jS|SdS)a;Improved version of pa.Table.cast. It supports casting to feature types stored in the schema metadata. Args: table (:obj:`pyarrow.Table`): PyArrow table to cast schema (:obj:`pyarrow.Schema`): target PyArrow schema. Returns: table (:obj:`pyarrow.Table`): the casted table N)r,rmetadatar)r'r,rrrrs   rcsddlm}|j|j}tdd|jDrg}g}x|jD]|jj}|j}tj j j rt |d s~|j |kr|j|j |jfddj Dq>|j||jjq>Wtjj||d}n|j }|j d d |fd d |jD|jjjS) aImproved version of pa.Table.flatten. It behaves as pa.Table.flatten in a sense it does 1-step flatten of the columns with a struct type into one column per struct field, but updates the metadata and skips decodable features unless the `decode` attribute of these features is set to False. Args: table (Table): PyArrow table to flatten Returns: Table: the flattened table r )rcss$|]}t|do|j|kVqdS)rN)rr)r.rrrrr0sz table_flatten..rcsg|]}jd|jqS)rI)ro)r.r)rrrrQsz!table_flatten..)r)Z max_depthcsi|]}||qSrr)r.Z column_name) flat_featuresrrr|sz!table_flatten..)rrrr,anyrrrorrrrrrrrrrrrrr)r'rrZ flat_arraysZflat_column_namesrrZ flat_tabler)rrrrs*        r)r'functioncsTddlm}m|j|j}fddx"|jD]\}}|||q6WdS)zVisit all arrays in a table and apply a function to them. Args: table (:obj:`pyarrow.Table`): PyArrow table to visit function (Callable[[pa.Array], None]): function to apply to each array r )rrcst|tjr(x|jD]}|qWnt|tjr:|j}|tjj|jrt d rtrtj t rfddj j Dxhj D]\}}|j ||qWnBtjj|jrttr|jdntr|jj dS)Nrcs i|]\}}|jd|qS))ra)ra)r.ror)rrrrr|sz1table_visitor.._visit..r)rzrrrrrrrrrrrr=rrrhr)rrrror)r_visitr)rrrs"       ztable_visitor.._visitN)rrrrr,r=)r'rrrrorr)rrrr table_visitors  r)r)T)T)@r?rsrmr functoolsr itertoolsrtypingrrrrrr r ZnumpyrUZpyarrowrrr Z utils.loggingr rrrrcrprrrr$rr(r)rfr7rrFrOrPrrr}rrrrrrrArrayZDataTyperr r rZSchemarrrrrrrrrsj  $     /\ = $ MZP)