text stringlengths 1 1.02k | class_index int64 0 271 | source stringclasses 76
values |
|---|---|---|
def __post_init__(self):
self.name = str(self.name) # Make sure we convert NamedSplits in strings
NamedSplit(self.name) # check that it's a valid split name
self.split_info = SplitInfo(name=self.name) | 97 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/splits.py |
class IndexedTableMixin:
def __init__(self, table: pa.Table):
self._schema: pa.Schema = table.schema
self._batches: List[pa.RecordBatch] = [
recordbatch for recordbatch in table.to_batches() if len(recordbatch) > 0
]
self._offsets: np.ndarray = np.cumsum([0] + [len(b) for... | 98 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
def fast_gather(self, indices: Union[List[int], np.ndarray]) -> pa.Table:
"""
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
... | 98 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
def fast_slice(self, offset=0, length=None) -> pa.Table:
"""
Slice the Table using interpolation search.
The behavior is the same as `pyarrow.Table.slice` but it's significantly faster. | 98 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
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.
"""
if offset < 0:
raise IndexError("Offset must be non-negative")
elif offset >= self._offsets[-1] or (length is... | 98 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
class Table(IndexedTableMixin):
"""
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, c... | 99 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
def __deepcopy__(self, memo: dict):
# arrow tables are immutable, so there's no need to copy self.table
# moreover calling deepcopy on a pyarrow table seems to make pa.total_allocated_bytes() decrease for some reason
# by adding it to the memo, self.table won't be copied
memo[id(self.tab... | 99 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Raises:
`pa.lib.ArrowInvalid`: if validation fails
"""
return self.table.validate(*args, **kwargs)
def equals(self, *args, **kwargs):
"""
Check if contents of two tables are equal.
Args:
other ([`~datasets.table.Table`]):
Table to com... | 99 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Args:
max_chunksize (`int`, defaults to `None`):
Maximum size for `RecordBatch` chunks. Individual chunks may be
smaller depending on the chunk layout of individual columns.
Returns:
`List[pyarrow.RecordBatch]`
"""
return self.table.to_bat... | 99 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Args:
memory_pool (`MemoryPool`, defaults to `None`):
Arrow MemoryPool to use for allocations. Uses the default memory
pool is not passed.
strings_to_categorical (`bool`, defaults to `False`):
Encode string (UTF8) and binary types to `pandas.Catego... | 99 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
timestamp_as_object (`bool`, defaults to `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 timest... | 99 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
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 (`bool`, defaults to `False`):
If `True`, generate one internal "block" for each column when
... | 99 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
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
... | 99 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Returns:
`pandas.Series` or `pandas.DataFrame`: `pandas.Series` or `pandas.DataFrame` depending on type of object
"""
return self.table.to_pandas(*args, **kwargs)
def to_string(self, *args, **kwargs):
return self.table.to_string(*args, **kwargs)
def to_reader(self, max_chun... | 99 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Args:
i (`Union[int, str]`):
The index or name of the field to retrieve.
Returns:
`pyarrow.Field`
"""
return self.table.field(*args, **kwargs)
def column(self, *args, **kwargs):
"""
Select a column by its column name, or numeric index... | 99 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
@property
def columns(self):
"""
List of all columns in numerical order.
Returns:
`List[pa.ChunkedArray]`
"""
return self.table.columns
@property
def num_columns(self):
"""
Number of columns in this table.
Returns:
in... | 99 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
@property
def nbytes(self):
"""
Total number of bytes consumed by the elements of the table.
"""
return self.table.nbytes
@property
def column_names(self):
"""
Names of the table's columns.
"""
return self.table.column_names
def __eq__(se... | 99 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Args:
offset (`int`, defaults to `0`):
Offset from start of table to slice.
length (`int`, defaults to `None`):
Length of slice (default is until end of table starting from
offset).
Returns:
`datasets.table.Table`
"""
... | 99 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
def combine_chunks(self, *args, **kwargs):
"""
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 (`MemoryPool`, defaults to `None`):
... | 99 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
def replace_schema_metadata(self, *args, **kwargs):
"""
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 (`dict`, defaults to `None... | 99 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Returns:
`datasets.table.Table`: New table with the passed column added.
"""
raise NotImplementedError()
def append_column(self, *args, **kwargs):
"""
Append column at end of columns.
Args:
field_ (`Union[str, pyarrow.Field]`):
If a s... | 99 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
def set_column(self, *args, **kwargs):
"""
Replace column in Table at position.
Args:
i (`int`):
Index to place the column at.
field_ (`Union[str, pyarrow.Field]`):
If a string is passed then the type is deduced from the column
... | 99 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Raises:
`KeyError` : if any of the passed columns name are not existing.
Returns:
`datasets.table.Table`: New table without the columns.
"""
raise NotImplementedError()
def select(self, *args, **kwargs):
"""
Select columns of the table.
Retu... | 99 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
class TableBlock(Table):
"""
`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`.
"""
pass | 100 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
class InMemoryTable(TableBlock):
"""
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 p... | 101 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
@classmethod
def from_pandas(cls, *args, **kwargs):
"""
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 translat... | 101 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Args:
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.... | 101 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
nthreads (`int`, defaults to `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 (`List[str]`, *optional*):
List of column to be converted. If `None`, use all column... | 101 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Returns:
`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)
<pya... | 101 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Args:
arrays (`List[Union[pyarrow.Array, pyarrow.ChunkedArray]]`):
Equal-length arrays that should form the table.
names (`List[str]`, *optional*):
Names for the table columns. If not passed, schema must be passed.
schema (`Schema`, defaults to `None`)... | 101 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Args:
mapping (`Union[dict, Mapping]`):
A mapping of strings to Arrays or Python lists.
schema (`Schema`, defaults to `None`):
If not passed, will be inferred from the Mapping values
metadata (`Union[dict, Mapping]`, defaults to `None`):
... | 101 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Returns:
`datasets.table.Table`
"""
return cls(pa.Table.from_pylist(mapping, *args, **kwargs))
@classmethod
def from_batches(cls, *args, **kwargs):
"""
Construct a Table from a sequence or iterator of Arrow `RecordBatches`.
Args:
batches (`Union[... | 101 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Args:
offset (`int`, defaults to `0`):
Offset from start of table to slice.
length (`int`, defaults to `None`):
Length of slice (default is until end of table starting from
offset).
Returns:
`datasets.table.Table`
"""
... | 101 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Returns:
`datasets.table.Table`
"""
return InMemoryTable(table_flatten(self.table, *args, **kwargs))
def combine_chunks(self, *args, **kwargs):
"""
Make a new table by combining the chunks this table has.
All the underlying chunks in the `ChunkedArray` of each c... | 101 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Returns:
`datasets.table.Table`
"""
return InMemoryTable(table_cast(self.table, *args, **kwargs))
def replace_schema_metadata(self, *args, **kwargs):
"""
EXPERIMENTAL: Create shallow copy of table by replacing schema
key-value metadata with the indicated new meta... | 101 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Args:
i (`int`):
Index to place the column at.
field_ (`Union[str, pyarrow.Field]`):
If a string is passed then the type is deduced from the column
data.
column (`Union[pyarrow.Array, List[pyarrow.Array]]`):
Column data.... | 101 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Returns:
`datasets.table.Table`:
New table with the passed column added.
"""
return InMemoryTable(self.table.append_column(*args, **kwargs))
def remove_column(self, *args, **kwargs):
"""
Create new Table with the indicated column removed.
Args:
... | 101 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Returns:
`datasets.table.Table`:
New table with the passed column set.
"""
return InMemoryTable(self.table.set_column(*args, **kwargs))
def rename_columns(self, *args, **kwargs):
"""
Create new table with columns renamed to provided names.
"""
... | 101 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Returns a new table with the specified columns, and metadata preserved.
Args:
columns (:obj:`Union[List[str], List[int]]`):
The column names or integer indices to select.
Returns:
:class:`datasets.table.Table`: New table with the specified columns, and metadata ... | 101 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
class MemoryMappedTable(TableBlock):
"""
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 transfor... | 102 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
def __init__(self, table: pa.Table, path: str, replays: Optional[List[Replay]] = None):
super().__init__(table)
self.path = os.path.abspath(path)
self.replays: List[Replay] = replays if replays is not None else []
@classmethod
def from_file(cls, filename: str, replays=None):
tab... | 102 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
@staticmethod
def _apply_replays(table: pa.Table, replays: Optional[List[Replay]] = None) -> pa.Table:
if replays is not None:
for name, args, kwargs in replays:
if name == "cast":
table = table_cast(table, *args, **kwargs)
elif name == "flatte... | 102 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Args:
offset (`int`, defaults to `0`):
Offset from start of table to slice.
length (`int`, defaults to `None`):
Length of slice (default is until end of table starting from
offset).
Returns:
`datasets.table.Table`
"""
... | 102 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
def flatten(self, *args, **kwargs):
"""
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 (`MemoryPool`, defaults to `None`):
For memory allocations, if requ... | 102 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Args:
memory_pool (`MemoryPool`, defaults to `None`):
For memory allocations, if required, otherwise use default pool.
Returns:
`datasets.table.Table`
"""
replay = ("combine_chunks", copy.deepcopy(args), copy.deepcopy(kwargs))
replays = self._appe... | 102 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Returns:
`datasets.table.Table`
"""
replay = ("cast", copy.deepcopy(args), copy.deepcopy(kwargs))
replays = self._append_replay(replay)
return MemoryMappedTable(table_cast(self.table, *args, **kwargs), self.path, replays)
def replace_schema_metadata(self, *args, **kwargs... | 102 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
A new table is returned with the column added, the original table
object is left unchanged.
Args:
i (`int`):
Index to place the column at.
field_ (`Union[str, pyarrow.Field]`):
If a string is passed then the type is deduced from the column
... | 102 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Args:
field_ (`Union[str, pyarrow.Field]`):
If a string is passed then the type is deduced from the column
data.
column (`Union[pyarrow.Array, List[pyarrow.Array]]`):
Column data.
Returns:
`datasets.table.Table`:
... | 102 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Returns:
`datasets.table.Table`:
New table without the column.
"""
replay = ("remove_column", copy.deepcopy(args), copy.deepcopy(kwargs))
replays = self._append_replay(replay)
return MemoryMappedTable(self.table.remove_column(*args, **kwargs), self.path, repla... | 102 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Returns:
`datasets.table.Table`:
New table with the passed column set.
"""
replay = ("set_column", copy.deepcopy(args), copy.deepcopy(kwargs))
replays = self._append_replay(replay)
return MemoryMappedTable(self.table.set_column(*args, **kwargs), self.path, rep... | 102 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Returns:
`datasets.table.Table`:
New table without the columns.
"""
replay = ("drop", copy.deepcopy(args), copy.deepcopy(kwargs))
replays = self._append_replay(replay)
return MemoryMappedTable(self.table.drop(*args, **kwargs), self.path, replays)
def sele... | 102 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
class ConcatenationTable(Table):
"""
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.... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
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 wh... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
def __init__(self, table: pa.Table, blocks: List[List[TableBlock]]):
super().__init__(table)
self.blocks = blocks
# Check that all the blocks have the right type.
# Only InMemoryTable and MemoryMappedTable are allowed.
for subtables in blocks:
for subtable in subtable... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
def __setstate__(self, state):
blocks = state["blocks"]
schema = state["schema"]
table = self._concat_blocks_horizontally_and_vertically(blocks)
if schema is not None and table.schema != schema:
# We fix the columns by concatenating with an empty table with the right columns
... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
@staticmethod
def _concat_blocks(blocks: List[Union[TableBlock, pa.Table]], axis: int = 0) -> pa.Table:
pa_tables = [table.table if hasattr(table, "table") else table for table in blocks]
if axis == 0:
# We set promote_options="default" to fill missing columns with null values
... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
@classmethod
def _concat_blocks_horizontally_and_vertically(cls, blocks: List[List[TableBlock]]) -> pa.Table:
pa_tables_to_concat_vertically = []
for i, tables in enumerate(blocks):
if not tables:
continue
pa_table_horizontally_concatenated = cls._concat_block... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
@classmethod
def _merge_blocks(cls, blocks: TableBlockContainer, axis: Optional[int] = None) -> TableBlockContainer:
if axis is not None:
merged_blocks = []
for is_in_memory, block_group in groupby(blocks, key=lambda x: isinstance(x, InMemoryTable)):
if is_in_memory:
... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
@classmethod
def _consolidate_blocks(cls, blocks: TableBlockContainer) -> TableBlockContainer:
if isinstance(blocks, TableBlock):
return blocks
elif isinstance(blocks[0], TableBlock):
return cls._merge_blocks(blocks, axis=0)
else:
return cls._merge_blocks(... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
@classmethod
def from_tables(cls, tables: List[Union[pa.Table, Table]], axis: int = 0) -> "ConcatenationTable":
"""Create `ConcatenationTable` from list of tables.
Args:
tables (list of `Table` or list of `pyarrow.Table`):
List of tables.
axis (`{0, 1}`, defa... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
def _slice_row_block(row_block: List[TableBlock], length: int) -> Tuple[List[TableBlock], List[TableBlock]]:
sliced = [table.slice(0, length) for table in row_block]
remainder = [table.slice(length, len(row_block[0]) - length) for table in row_block]
return sliced, remainder
... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
[ x x x | x x x ]
+ [ y y | y y | y y ]
-----------------------------
= [ x x | x | x | x x ]
[ y y | y | y | y y ] | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
"""
result, blocks = list(result), list(blocks)
new_result, new_blocks = [], []
while result and blocks:
# we slice the longest row block to save two row blocks of same length
# and we replace the long row block by its remainder if necessary
... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
raise ValueError("Failed to concatenate on axis=1 because tables don't have the same number of rows")
return new_result, new_blocks | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
def _extend_blocks(
result: List[List[TableBlock]], blocks: List[List[TableBlock]], axis: int = 0
) -> List[List[TableBlock]]:
if axis == 0:
result.extend(blocks)
elif axis == 1:
# We make sure each row_block have the same num_rows
... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
def slice(self, offset=0, length=None):
"""
Compute zero-copy slice of this Table.
Args:
offset (`int`, defaults to `0`):
Offset from start of table to slice.
length (`int`, defaults to `None`):
Length of slice (default is until end of tab... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Returns:
`datasets.table.Table`
"""
table = self.table.slice(offset, length=length)
length = length if length is not None else self.num_rows - offset
blocks = []
for tables in self.blocks:
n_rows = len(tables[0])
if length == 0:
... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
def filter(self, mask, *args, **kwargs):
"""
Select records from a Table. See `pyarrow.compute.filter` for full usage.
"""
table = self.table.filter(mask, *args, **kwargs)
blocks = []
for (offset, length), tables in zip(self._slices, self.blocks):
submask = ma... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Returns:
`datasets.table.Table`
"""
table = table_flatten(self.table, *args, **kwargs)
blocks = []
for tables in self.blocks:
blocks.append([t.flatten(*args, **kwargs) for t in tables])
return ConcatenationTable(table, blocks)
def combine_chunks(self,... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
def cast(self, target_schema, *args, **kwargs):
"""
Cast table values to another schema.
Args:
target_schema (`Schema`):
Schema to cast to, the names and order of fields must match.
safe (`bool`, defaults to `True`):
Check for overflows or... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
table = table_cast(self.table, target_schema, *args, **kwargs)
target_features = Features.from_arrow_schema(target_schema)
blocks = []
for subtables in self.blocks:
new_tables = []
fields = list(target_schema)
for subtable in subtables:
subfiel... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
def replace_schema_metadata(self, *args, **kwargs):
"""
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 (`dict`, defaults to `... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Args:
i (`int`):
Index to place the column at.
field_ (`Union[str, pyarrow.Field]`):
If a string is passed then the type is deduced from the column
data.
column (`Union[pyarrow.Array, List[pyarrow.Array]]`):
Column data.... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
def remove_column(self, i, *args, **kwargs):
"""
Create new Table with the indicated column removed.
Args:
i (`int`):
Index of column to remove.
Returns:
`datasets.table.Table`:
New table without the column.
"""
ta... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Args:
i (`int`):
Index to place the column at.
field_ (`Union[str, pyarrow.Field]`):
If a string is passed then the type is deduced from the column
data.
column (`Union[pyarrow.Array, List[pyarrow.Array]]`):
Column data.... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
def drop(self, columns, *args, **kwargs):
"""
Drop one or more columns and return a new table.
Args:
columns (`List[str]`):
List of field names referencing existing columns.
Raises:
`KeyError` : if any of the passed columns name are not existing.... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
Args:
columns (:obj:`Union[List[str], List[int]]`):
The column names or integer indices to select.
Returns:
:class:`datasets.table.Table`: New table with the specified columns, and metadata preserved.
"""
table = self.table.select(columns, *args, **kwargs... | 103 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
class CastError(ValueError):
"""When it's not possible to cast an Arrow table to a specific schema or set of features"""
def __init__(self, *args, table_column_names: List[str], requested_column_names: List[str]) -> None:
super().__init__(*args)
self.table_column_names = table_column_names
... | 104 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
def details(self):
new_columns = set(self.table_column_names) - set(self.requested_column_names)
missing_columns = set(self.requested_column_names) - set(self.table_column_names)
if new_columns and missing_columns:
return f"there are {len(new_columns)} new columns ({_short_str(new_co... | 104 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/table.py |
class _InitializeConfiguredDatasetBuilder:
"""
From https://stackoverflow.com/questions/4647566/pickle-a-dynamically-parameterized-sub-class
See also ConfiguredDatasetBuilder.__reduce__
When called with the param value as the only argument, returns an
un-initialized instance of the parameterized cla... | 105 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
class ConfiguredDatasetBuilder(builder_cls):
BUILDER_CONFIGS = builder_configs
DEFAULT_CONFIG_NAME = default_config_name
__module__ = builder_cls.__module__ # so that the actual packaged builder can be imported
def __reduce__(self): # to make dynamically created class pickable, see _... | 106 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
class BuilderConfigsParameters:
"""Dataclass containing objects related to creation of builder configurations from yaml's metadata content.
Attributes:
metadata_configs (`MetadataConfigs`, *optional*):
Configs parsed from yaml's metadata.
builder_configs (`list[BuilderConfig]`, *opt... | 107 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
class DatasetModule:
module_path: str
hash: str
builder_kwargs: dict
builder_configs_parameters: BuilderConfigsParameters = field(default_factory=BuilderConfigsParameters)
dataset_infos: Optional[DatasetInfosDict] = None
importable_file_path: Optional[str] = None | 108 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
class _DatasetModuleFactory:
def get_module(self) -> DatasetModule:
raise NotImplementedError | 109 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
class LocalDatasetModuleFactoryWithScript(_DatasetModuleFactory):
"""Get the module of a local dataset. The dataset script is loaded from a local script."""
def __init__(
self,
path: str,
download_config: Optional[DownloadConfig] = None,
download_mode: Optional[Union[DownloadMod... | 110 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
def get_module(self) -> DatasetModule:
if config.HF_DATASETS_TRUST_REMOTE_CODE and self.trust_remote_code is None:
warnings.warn(
f"The repository for {self.name} contains custom code which must be executed to correctly "
f"load the dataset. You can inspect the reposi... | 110 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
base_path=str(Path(self.path).parent),
imports=imports,
download_config=self.download_config,
)
additional_files = []
if dataset_infos_path.is_file():
additional_files.append((config.DATASETDICT_INFOS_FILENAME, str(dataset_infos_path)))
if dataset_read... | 110 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
trust_remote_code = resolve_trust_remote_code(self.trust_remote_code, self.name)
if trust_remote_code:
_create_importable_file(
local_path=self.path,
local_imports=local_imports,
additional_files=additional_files,
... | 110 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
_check_library_imports(name=self.name, library_imports=library_imports)
module_path, hash = _load_importable_file(
dynamic_modules_path=dynamic_modules_path,
module_namespace="datasets",
subdirectory_name=hash,
name=self.name,
) | 110 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
# make the new module to be noticed by the import system
importlib.invalidate_caches()
builder_kwargs = {"base_path": str(Path(self.path).parent)}
return DatasetModule(module_path, hash, builder_kwargs, importable_file_path=importable_file_path) | 110 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
class LocalDatasetModuleFactoryWithoutScript(_DatasetModuleFactory):
"""Get the module of a dataset loaded from the user's data files. The dataset builder module to use is inferred
from the data files extensions."""
def __init__(
self,
path: str,
data_dir: Optional[str] = None,
... | 111 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
def get_module(self) -> DatasetModule:
readme_path = os.path.join(self.path, config.REPOCARD_FILENAME)
standalone_yaml_path = os.path.join(self.path, config.REPOYAML_FILENAME)
dataset_card_data = DatasetCard.load(readme_path).data if os.path.isfile(readme_path) else DatasetCardData()
if ... | 111 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
# because we need to infer module name by files extensions
base_path = Path(self.path, self.data_dir or "").expanduser().resolve().as_posix()
if self.data_files is not None:
patterns = sanitize_patterns(self.data_files)
elif metadata_configs and not self.data_dir and "data_files" in ... | 111 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
supports_metadata = module_name in _MODULE_SUPPORTS_METADATA
if self.data_files is None and supports_metadata:
try:
metadata_patterns = get_metadata_patterns(base_path)
except FileNotFoundError:
metadata_patterns = None
if metadata_patterns is ... | 111 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
module_path, _ = _PACKAGED_DATASETS_MODULES[module_name]
if metadata_configs:
builder_configs, default_config_name = create_builder_configs_from_metadata_configs(
module_path,
metadata_configs,
base_path=base_path,
supports_metadata=sup... | 111 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
# this file is deprecated and was created automatically in old versions of push_to_hub
if os.path.isfile(os.path.join(self.path, config.DATASETDICT_INFOS_FILENAME)):
with open(os.path.join(self.path, config.DATASETDICT_INFOS_FILENAME), encoding="utf-8") as f:
legacy_dataset_infos = D... | 111 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
if default_config_name is None and len(dataset_infos) == 1:
default_config_name = next(iter(dataset_infos)) | 111 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
hash = Hasher.hash({"dataset_infos": dataset_infos, "builder_configs": builder_configs})
return DatasetModule(
module_path,
hash,
builder_kwargs,
dataset_infos=dataset_infos,
builder_configs_parameters=BuilderConfigsParameters(
metadata... | 111 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
class PackagedDatasetModuleFactory(_DatasetModuleFactory):
"""Get the dataset builder module from the ones that are packaged with the library: csv, json, etc."""
def __init__(
self,
name: str,
data_dir: Optional[str] = None,
data_files: Optional[Union[str, List, Dict]] = None,
... | 112 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
def get_module(self) -> DatasetModule:
base_path = Path(self.data_dir or "").expanduser().resolve().as_posix()
patterns = (
sanitize_patterns(self.data_files)
if self.data_files is not None
else get_data_patterns(base_path, download_config=self.download_config)
... | 112 | /Users/nielsrogge/Documents/python_projecten/datasets/src/datasets/load.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.