DataChain
The DataChain
class creates a data chain, which is a sequence of data manipulation
steps such as reading data from storages, running AI or LLM models or calling external
services API to validate or enrich data. See DataChain
for examples of how to create a chain.
Column
Bases: ColumnClause
Source code in datachain/query/schema.py
glob
read_csv
read_csv(
path,
delimiter: Optional[str] = None,
header: bool = True,
output: OutputType = None,
column: str = "",
model_name: str = "",
source: bool = True,
nrows=None,
session: Optional[Session] = None,
settings: Optional[dict] = None,
column_types: Optional[
dict[str, Union[str, DataType]]
] = None,
parse_options: Optional[
dict[str, Union[str, Union[bool, Callable]]]
] = None,
**kwargs
) -> DataChain
Generate chain from csv files.
Parameters:
-
path
–Storage URI with directory. URI must start with storage prefix such as
s3://
,gs://
,az://
or "file:///". -
delimiter
–Character for delimiting columns. Takes precedence if also specified in
parse_options
. Defaults to ",". -
header
–Whether the files include a header row.
-
output
–Dictionary or feature class defining column names and their corresponding types. List of column names is also accepted, in which case types will be inferred.
-
column
–Created column name.
-
model_name
–Generated model name.
-
source
–Whether to include info about the source file.
-
nrows
–Optional row limit.
-
session
–Session to use for the chain.
-
settings
–Settings to use for the chain.
-
column_types
–Dictionary of column names and their corresponding types. It is passed to CSV reader and for each column specified type auto inference is disabled.
-
parse_options
(Optional[dict[str, Union[str, Union[bool, Callable]]]]
, default:None
) –Tells the parser how to process lines. See https://arrow.apache.org/docs/python/generated/pyarrow.csv.ParseOptions.html
Example
Reading a csv file:
Reading csv files from a directory as a combined dataset:
Source code in datachain/lib/dc/csv.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 |
|
read_dataset
read_dataset(
name: str,
namespace: Optional[str] = None,
project: Optional[str] = None,
version: Optional[Union[str, int]] = None,
session: Optional[Session] = None,
settings: Optional[dict] = None,
delta: Optional[bool] = False,
delta_on: Optional[Union[str, Sequence[str]]] = (
"file.path",
"file.etag",
"file.version",
),
delta_result_on: Optional[
Union[str, Sequence[str]]
] = None,
delta_compare: Optional[
Union[str, Sequence[str]]
] = None,
delta_retry: Optional[Union[bool, str]] = None,
update: bool = False,
) -> DataChain
Get data from a saved Dataset. It returns the chain itself. If dataset or version is not found locally, it will try to pull it from Studio.
Parameters:
-
name
(str
) –The dataset name, which can be a fully qualified name including the namespace and project. Alternatively, it can be a regular name, in which case the explicitly defined namespace and project will be used if they are set; otherwise, default values will be applied.
-
namespace
–optional name of namespace in which dataset to read is created
-
project
–optional name of project in which dataset to read is created
-
version
–dataset version. Supports: - Exact version strings: "1.2.3" - Legacy integer versions: 1, 2, 3 (finds latest major version) - Version specifiers (PEP 440): ">=1.0.0,<2.0.0", "~=1.4.2", "==1.2.*", etc.
-
session
–Session to use for the chain.
-
settings
–Settings to use for the chain.
-
delta
(Optional[bool]
, default:False
) –If True, only process new or changed files instead of reprocessing everything. This saves time by skipping files that were already processed in previous versions. The optimization is working when a new version of the dataset is created. Default is False.
-
delta_on
(Optional[Union[str, Sequence[str]]]
, default:('file.path', 'file.etag', 'file.version')
) –Field(s) that uniquely identify each record in the source data. Used to detect which records are new or changed. Default is ("file.path", "file.etag", "file.version").
-
delta_result_on
(Optional[Union[str, Sequence[str]]]
, default:None
) –Field(s) in the result dataset that match
delta_on
fields. Only needed if you rename the identifying fields during processing. Default is None. -
delta_compare
(Optional[Union[str, Sequence[str]]]
, default:None
) –Field(s) used to detect if a record has changed. If not specified, all fields except
delta_on
fields are used. Default is None. -
delta_retry
(Optional[Union[bool, str]]
, default:None
) –Controls retry behavior for failed records: - String (field name): Reprocess records where this field is not empty (error mode) - True: Reprocess records missing from the result dataset (missing mode) - None: No retry processing (default)
-
update
(bool
, default:False
) –If True always checks for newer versions available on Studio, even if some version of the dataset exists locally already. If False (default), it will only fetch the dataset from Studio if it is not found locally.
Example
# Legacy integer version support (finds latest in major version)
chain = dc.read_dataset("my_cats", version=1) # Latest 1.x.x version
Source code in datachain/lib/dc/datasets.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
|
datasets
datasets(
session: Optional[Session] = None,
settings: Optional[dict] = None,
in_memory: bool = False,
column: Optional[str] = None,
include_listing: bool = False,
studio: bool = False,
attrs: Optional[list[str]] = None,
) -> DataChain
Generate chain with list of registered datasets.
Parameters:
-
session
(Optional[Session]
, default:None
) –Optional session instance. If not provided, uses default session.
-
settings
(Optional[dict]
, default:None
) –Optional dictionary of settings to configure the chain.
-
in_memory
(bool
, default:False
) –If True, creates an in-memory session. Defaults to False.
-
column
(Optional[str]
, default:None
) –Name of the output column in the chain. Defaults to None which means no top level column will be created.
-
include_listing
(bool
, default:False
) –If True, includes listing datasets. Defaults to False.
-
studio
(bool
, default:False
) –If True, returns datasets from Studio only, otherwise returns all local datasets. Defaults to False.
-
attrs
(Optional[list[str]]
, default:None
) –Optional list of attributes to filter datasets on. It can be just attribute without value e.g "NLP", or attribute with value e.g "location=US". Attribute with value can also accept "" to target all that have specific name e.g "location="
Returns:
-
DataChain
(DataChain
) –A new DataChain instance containing dataset information.
Example
Source code in datachain/lib/dc/datasets.py
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 |
|
delete_dataset
delete_dataset(
name: str,
namespace: Optional[str] = None,
project: Optional[str] = None,
version: Optional[str] = None,
force: Optional[bool] = False,
studio: Optional[bool] = False,
session: Optional[Session] = None,
in_memory: bool = False,
) -> None
Removes specific dataset version or all dataset versions, depending on a force flag.
Parameters:
-
name
(str
) –The dataset name, which can be a fully qualified name including the namespace and project. Alternatively, it can be a regular name, in which case the explicitly defined namespace and project will be used if they are set; otherwise, default values will be applied.
-
namespace
–optional name of namespace in which dataset to delete is created
-
project
–optional name of project in which dataset to delete is created
-
version
–Optional dataset version
-
force
(Optional[bool]
, default:False
) –If true, all datasets versions will be removed. Defaults to False.
-
studio
(Optional[bool]
, default:False
) –If True, removes dataset from Studio only, otherwise removes local dataset. Defaults to False.
-
session
(Optional[Session]
, default:None
) –Optional session instance. If not provided, uses default session.
-
in_memory
(bool
, default:False
) –If True, creates an in-memory session. Defaults to False.
Returns: None
Example
Source code in datachain/lib/dc/datasets.py
move_dataset
move_dataset(
src: str,
dest: str,
session: Optional[Session] = None,
in_memory: bool = False,
) -> None
Moves an entire dataset between namespaces and projects.
Parameters:
-
src
(str
) –The source dataset name. This can be a fully qualified name that includes the namespace and project, or a regular name. If a regular name is used, default values will be applied. The source dataset will no longer exist after the move.
-
dest
(str
) –The destination dataset name. This can also be a fully qualified name with a namespace and project, or just a regular name (default values will be used in that case). The original dataset will be moved here.
-
session
(Optional[Session]
, default:None
) –An optional session instance. If not provided, the default session will be used.
-
in_memory
(bool
, default:False
) –If True, creates an in-memory session. Defaults to False.
Returns:
-
None
–None
Examples:
Source code in datachain/lib/dc/datasets.py
read_hf
read_hf(
dataset: Union[str, HFDatasetType],
*args,
session: Optional[Session] = None,
settings: Optional[dict] = None,
column: str = "",
model_name: str = "",
**kwargs
) -> DataChain
Generate chain from huggingface hub dataset.
Parameters:
-
dataset
–Path or name of the dataset to read from Hugging Face Hub, or an instance of
datasets.Dataset
-like object. -
session
–Session to use for the chain.
-
settings
–Settings to use for the chain.
-
column
–Generated object column name.
-
model_name
–Generated model name.
-
kwargs
–Parameters to pass to datasets.load_dataset.
Example
Load from Hugging Face Hub:
Generate chain from loaded dataset:
Source code in datachain/lib/dc/hf.py
read_json
read_json(
path: Union[str, PathLike[str]],
type: FileType = "text",
spec: Optional[DataType] = None,
schema_from: Optional[str] = "auto",
jmespath: Optional[str] = None,
column: Optional[str] = "",
model_name: Optional[str] = None,
format: Optional[str] = "json",
nrows=None,
**kwargs
) -> DataChain
Get data from JSON. It returns the chain itself.
Parameters:
-
path
–storage URI with directory. URI must start with storage prefix such as
s3://
,gs://
,az://
or "file:///" -
type
–read file as "binary", "text", or "image" data. Default is "text".
-
spec
–optional Data Model
-
schema_from
–path to sample to infer spec (if schema not provided)
-
column
–generated column name
-
model_name
–optional generated model name
-
format
(Optional[str]
, default:'json'
) –"json", "jsonl"
-
jmespath
–optional JMESPATH expression to reduce JSON
-
nrows
–optional row limit for jsonl and JSON arrays
Example
infer JSON schema from data, reduce using JMESPATH
infer JSON schema from a particular path
Source code in datachain/lib/dc/json.py
listings
listings(
session: Optional[Session] = None,
in_memory: bool = False,
column: str = "listing",
**kwargs
) -> DataChain
Generate chain with list of cached listings. Listing is a special kind of dataset which has directory listing data of some underlying storage (e.g S3 bucket).
Source code in datachain/lib/dc/listings.py
read_pandas
read_pandas(
df: DataFrame,
name: str = "",
session: Optional[Session] = None,
settings: Optional[dict] = None,
in_memory: bool = False,
column: str = "",
) -> DataChain
Generate chain from pandas data-frame.
Example
Source code in datachain/lib/dc/pandas.py
read_parquet
read_parquet(
path,
partitioning: Any = "hive",
output: Optional[dict[str, DataType]] = None,
column: str = "",
model_name: str = "",
source: bool = True,
session: Optional[Session] = None,
settings: Optional[dict] = None,
**kwargs
) -> DataChain
Generate chain from parquet files.
Parameters:
-
path
–Storage URI with directory. URI must start with storage prefix such as
s3://
,gs://
,az://
or "file:///". -
partitioning
–Any pyarrow partitioning schema.
-
output
–Dictionary defining column names and their corresponding types.
-
column
–Created column name.
-
model_name
–Generated model name.
-
source
–Whether to include info about the source file.
-
session
–Session to use for the chain.
-
settings
–Settings to use for the chain.
Example
Reading a single file:
Reading a partitioned dataset from a directory:
Source code in datachain/lib/dc/parquet.py
read_records
read_records(
to_insert: Optional[Union[dict, Iterable[dict]]],
session: Optional[Session] = None,
settings: Optional[dict] = None,
in_memory: bool = False,
schema: Optional[dict[str, DataType]] = None,
) -> DataChain
Create a DataChain from the provided records. This method can be used for programmatically generating a chain in contrast of reading data from storages or other sources.
Parameters:
-
to_insert
–records (or a single record) to insert. Each record is a dictionary of signals and theirs values.
-
schema
–describes chain signals and their corresponding types
Notes
This call blocks until all records are inserted.
Source code in datachain/lib/dc/records.py
read_storage
read_storage(
uri: Union[
str, PathLike[str], list[str], list[PathLike[str]]
],
*,
type: FileType = "binary",
session: Optional[Session] = None,
settings: Optional[dict] = None,
in_memory: bool = False,
recursive: Optional[bool] = True,
column: str = "file",
update: bool = False,
anon: bool = False,
delta: Optional[bool] = False,
delta_on: Optional[Union[str, Sequence[str]]] = (
"file.path",
"file.etag",
"file.version",
),
delta_result_on: Optional[
Union[str, Sequence[str]]
] = None,
delta_compare: Optional[
Union[str, Sequence[str]]
] = None,
delta_retry: Optional[Union[bool, str]] = None,
client_config: Optional[dict] = None
) -> DataChain
Get data from storage(s) as a list of file with all file attributes. It returns the chain itself as usual.
Parameters:
-
uri
–storage URI with directory or list of URIs. URIs must start with storage prefix such as
s3://
,gs://
,az://
or "file:///" -
type
–read file as "binary", "text", or "image" data. Default is "binary".
-
recursive
–search recursively for the given path.
-
column
–Created column name.
-
update
–force storage reindexing. Default is False.
-
anon
–If True, we will treat cloud bucket as public one
-
client_config
–Optional client configuration for the storage client.
-
delta
(Optional[bool]
, default:False
) –If True, only process new or changed files instead of reprocessing everything. This saves time by skipping files that were already processed in previous versions. The optimization is working when a new version of the dataset is created. Default is False.
-
delta_on
(Optional[Union[str, Sequence[str]]]
, default:('file.path', 'file.etag', 'file.version')
) –Field(s) that uniquely identify each record in the source data. Used to detect which records are new or changed. Default is ("file.path", "file.etag", "file.version").
-
delta_result_on
(Optional[Union[str, Sequence[str]]]
, default:None
) –Field(s) in the result dataset that match
delta_on
fields. Only needed if you rename the identifying fields during processing. Default is None. -
delta_compare
(Optional[Union[str, Sequence[str]]]
, default:None
) –Field(s) used to detect if a record has changed. If not specified, all fields except
delta_on
fields are used. Default is None. -
delta_retry
(Optional[Union[bool, str]]
, default:None
) –Controls retry behavior for failed records: - String (field name): Reprocess records where this field is not empty (error mode) - True: Reprocess records missing from the result dataset (missing mode) - None: No retry processing (default)
Returns:
-
DataChain
(DataChain
) –A DataChain object containing the file information.
Examples:
Simple call from s3:
Multiple URIs:
With AWS S3-compatible storage:
chain = dc.read_storage(
"s3://my-bucket/my-dir",
client_config = {"aws_endpoint_url": "<minio-endpoint-url>"}
)
Pass existing session
session = Session.get()
chain = dc.read_storage([
"path/to/dir1",
"path/to/dir2"
], session=session, recursive=True)
Note
When using multiple URIs with update=True
, the function optimizes by
avoiding redundant updates for URIs pointing to the same storage location.
Source code in datachain/lib/dc/storage.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 |
|
read_values
read_values(
ds_name: str = "",
session: Optional[Session] = None,
settings: Optional[dict] = None,
in_memory: bool = False,
output: OutputType = None,
column: str = "",
**fr_map
) -> DataChain
Generate chain from list of values.
Source code in datachain/lib/dc/values.py
read_database
read_database(
query: Union[str, Executable],
connection: ConnectionType,
params: Union[
Sequence[Mapping[str, Any]], Mapping[str, Any], None
] = None,
*,
output: Optional[dict[str, DataType]] = None,
session: Optional[Session] = None,
settings: Optional[dict] = None,
in_memory: bool = False,
infer_schema_length: Optional[int] = 100
) -> DataChain
Read the results of a SQL query into a DataChain, using a given database connection.
Parameters:
-
query
(Union[str, Executable]
) –The SQL query to execute. Can be a raw SQL string or a SQLAlchemy
Executable
object. -
connection
(ConnectionType
) –SQLAlchemy connectable, str, or a sqlite3 connection Using SQLAlchemy makes it possible to use any DB supported by that library. If a DBAPI2 object, only sqlite3 is supported. The user is responsible for engine disposal and connection closure for the SQLAlchemy connectable; str connections are closed automatically.
-
params
(Union[Sequence[Mapping[str, Any]], Mapping[str, Any], None]
, default:None
) –Parameters to pass to execute method.
-
output
(Optional[dict[str, DataType]]
, default:None
) –A dictionary mapping column names to types, used to override the schema inferred from the query results.
-
session
(Optional[Session]
, default:None
) –Session to use for the chain.
-
settings
(Optional[dict]
, default:None
) –Settings to use for the chain.
-
in_memory
(bool
, default:False
) –If True, creates an in-memory session. Defaults to False.
-
infer_schema_length
(Optional[int]
, default:100
) –The maximum number of rows to scan for inferring schema. If set to
None
, the full data may be scanned. The rows used for schema inference are stored in memory, so large values can lead to high memory usage. Only applies if theoutput
parameter is not set for the given column.
Examples:
Reading from a SQL query against a user-supplied connection:
query = "SELECT key, value FROM tbl"
chain = dc.read_database(query, connection, output={"value": float})
Load data from a SQLAlchemy driver/engine:
from sqlalchemy import create_engine
engine = create_engine("postgresql+psycopg://myuser:mypassword@localhost:5432/mydb")
chain = dc.read_database("select * from tbl", engine)
Load data from a parameterized SQLAlchemy query:
query = "SELECT key, value FROM tbl WHERE value > :value"
dc.read_database(query, engine, params={"value": 50})
Notes
- This function works with a variety of databases — including, but not limited to, SQLite, DuckDB, PostgreSQL, and Snowflake, provided the appropriate driver is installed.
- This call is blocking, and will execute the query and return once the results are saved.
Source code in datachain/lib/dc/database.py
ConnectionType
module-attribute
ConnectionType = Union[
str,
URL,
Connectable,
Engine,
Connection,
Session,
Connection,
]
DataChain
DataChain(
query: DatasetQuery,
settings: Settings,
signal_schema: SignalSchema,
setup: Optional[dict] = None,
_sys: bool = False,
)
DataChain - a data structure for batch data processing and evaluation.
It represents a sequence of data manipulation steps such as reading data from storages, running AI or LLM models or calling external services API to validate or enrich data.
Data in DataChain is presented as Python classes with arbitrary set of fields,
including nested classes. The data classes have to inherit from DataModel
class.
The supported set of field types include: majority of the type supported by the
underlyind library Pydantic
.
See Also
read_storage("s3://my-bucket/my-dir/")
- reading unstructured
data files from storages such as S3, gs or Azure ADLS.
DataChain.save("name")
- saving to a dataset.
read_dataset("name")
- reading from a dataset.
read_values(fib=[1, 2, 3, 5, 8])
- generating from values.
read_pandas(pd.DataFrame(...))
- generating from pandas.
read_json("file.json")
- generating from json.
read_csv("file.csv")
- generating from csv.
read_parquet("file.parquet")
- generating from parquet.
Example
import os
from mistralai.client import MistralClient
from mistralai.models.chat_completion import ChatMessage
import datachain as dc
PROMPT = (
"Was this bot dialog successful? "
"Describe the 'result' as 'Yes' or 'No' in a short JSON"
)
model = "mistral-large-latest"
api_key = os.environ["MISTRAL_API_KEY"]
chain = (
dc.read_storage("gs://datachain-demo/chatbot-KiT/")
.limit(5)
.settings(cache=True, parallel=5)
.map(
mistral_response=lambda file: MistralClient(api_key=api_key)
.chat(
model=model,
response_format={"type": "json_object"},
messages=[
ChatMessage(role="user", content=f"{PROMPT}: {file.read()}")
],
)
.choices[0]
.message.content,
)
.persist()
)
try:
print(chain.select("mistral_response").results())
except Exception as e:
print(f"do you have the right Mistral API key? {e}")
Source code in datachain/lib/dc/datachain.py
__iter__
Make DataChain objects iterable.
Yields:
-
tuple[DataValue, ...]
–Yields tuples of all column values for each row.
Source code in datachain/lib/dc/datachain.py
__or__
__repr__
__repr__() -> str
Return a string representation of the chain.
Source code in datachain/lib/dc/datachain.py
agg
agg(
func: Optional[Callable] = None,
partition_by: Optional[PartitionByType] = None,
params: Union[None, str, Sequence[str]] = None,
output: OutputType = None,
**signal_map: Callable
) -> Self
Aggregate rows using partition_by
statement and apply a function to the
groups of aggregated rows. The function needs to return new objects for each
group of the new rows. It returns a chain itself with new signals.
Input-output relationship: N:M
This method bears similarity to gen()
and map()
, employing a comparable set
of parameters, yet differs in two crucial aspects:
- The
partition_by
parameter: This specifies the column name or a list of column names that determine the grouping criteria for aggregation. - Group-based UDF function input: Instead of individual rows, the function
receives a list of all rows within each group defined by
partition_by
.
If partition_by
is not set or is an empty list, all rows will be placed
into a single group.
Parameters:
-
func
(Optional[Callable]
, default:None
) –Function applied to each group of rows.
-
partition_by
(Optional[PartitionByType]
, default:None
) –Column name(s) to group by. If None, all rows go into one group.
-
params
(Union[None, str, Sequence[str]]
, default:None
) –List of column names used as input for the function. Default is taken from function signature.
-
output
(OutputType
, default:None
) –Dictionary defining new signals and their corresponding types. Default type is taken from function signature.
-
**signal_map
(Callable
, default:{}
) –kwargs can be used to define
func
together with its return signal name in format ofagg(result_column=my_func)
.
Examples:
Basic aggregation with lambda function:
chain = chain.agg(
total=lambda category, amount: [sum(amount)],
output=float,
partition_by="category",
)
chain.save("new_dataset")
An alternative syntax, when you need to specify a more complex function:
# It automatically resolves which columns to pass to the function
# by looking at the function signature.
def agg_sum(
file: list[File], amount: list[float]
) -> Iterator[tuple[File, float]]:
yield file[0], sum(amount)
chain = chain.agg(
agg_sum,
output={"file": File, "total": float},
# Alternative syntax is to use `C` (short for Column) to specify
# a column name or a nested column, e.g. C("file.path").
partition_by=C("category"),
)
chain.save("new_dataset")
Using complex signals for partitioning (File
or any Pydantic BaseModel
):
def my_agg(files: list[File]) -> Iterator[tuple[File, int]]:
yield files[0], sum(f.size for f in files)
chain = chain.agg(
my_agg,
params=("file",),
output={"file": File, "total": int},
partition_by="file", # Column referring to all sub-columns of File
)
chain.save("new_dataset")
Aggregating all rows into a single group (when partition_by
is not set):
chain = chain.agg(
total_size=lambda file, size: [sum(size)],
output=int,
# No partition_by specified - all rows go into one group
)
chain.save("new_dataset")
Multiple partition columns:
chain = chain.agg(
total=lambda category, subcategory, amount: [sum(amount)],
output=float,
partition_by=["category", "subcategory"],
)
chain.save("new_dataset")
Source code in datachain/lib/dc/datachain.py
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 |
|
apply
Apply any function to the chain.
Useful for reusing in a chain of operations.
Example
Source code in datachain/lib/dc/datachain.py
avg
avg(col: str) -> StandardType
Compute the average of a column.
Parameters:
-
col
(str
) –The column to compute the average for.
Returns:
-
StandardType
–The average of the column values.
Source code in datachain/lib/dc/datachain.py
batch_map
batch_map(
func: Optional[Callable] = None,
params: Union[None, str, Sequence[str]] = None,
output: OutputType = None,
batch: int = 1000,
**signal_map
) -> Self
This is a batch version of map()
.
Input-output relationship: N:N
It accepts the same parameters plus an additional parameter:
batch : Size of each batch passed to `func`. Defaults to 1000.
Example
Source code in datachain/lib/dc/datachain.py
c
Returns Column instance attached to the current chain.
chunk
Split a chain into smaller chunks for e.g. parallelization.
Parameters:
Example
Note
Bear in mind that index
is 0-indexed but total
isn't.
Use 0/3, 1/3 and 2/3, not 1/3, 2/3 and 3/3.
Source code in datachain/lib/dc/datachain.py
clone
collect
Deprecated. Use to_iter
method instead.
Source code in datachain/lib/dc/datachain.py
column
Returns Column instance with a type if name is found in current schema, otherwise raises an exception.
Source code in datachain/lib/dc/datachain.py
count
count() -> int
diff
diff(
other: DataChain,
on: Union[str, Sequence[str]],
right_on: Optional[Union[str, Sequence[str]]] = None,
compare: Optional[Union[str, Sequence[str]]] = None,
right_compare: Optional[
Union[str, Sequence[str]]
] = None,
added: bool = True,
deleted: bool = True,
modified: bool = True,
same: bool = False,
status_col: Optional[str] = None,
) -> DataChain
Calculate differences between two chains.
This method identifies records that are added, deleted, modified, or unchanged between two chains. It adds a status column with values: A=added, D=deleted, M=modified, S=same.
Parameters:
-
other
(DataChain
) –Chain to compare against.
-
on
(Union[str, Sequence[str]]
) –Column(s) to match records between chains.
-
right_on
(Optional[Union[str, Sequence[str]]]
, default:None
) –Column(s) in the other chain to match against. Defaults to
on
. -
compare
(Optional[Union[str, Sequence[str]]]
, default:None
) –Column(s) to check for changes. If not specified,all columns are used.
-
right_compare
(Optional[Union[str, Sequence[str]]]
, default:None
) –Column(s) in the other chain to compare against. Defaults to values of
compare
. -
added
(bool
, default:True
) –Include records that exist in this chain but not in the other.
-
deleted
(bool
, default:True
) –Include records that exist only in the other chain.
-
modified
(bool
, default:True
) –Include records that exist in both but have different values.
-
same
(bool
, default:False
) –Include records that are identical in both chains.
-
status_col
(str
, default:None
) –Name for the status column showing differences.
Default behavior: By default, shows added, deleted, and modified records, but excludes unchanged records (same=False). Status column is not created.
Example
Source code in datachain/lib/dc/datachain.py
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 |
|
distinct
Removes duplicate rows based on uniqueness of some input column(s) i.e if rows are found with the same value of input column(s), only one row is left in the result set.
Source code in datachain/lib/dc/datachain.py
exec
explode
explode(
col: str,
model_name: Optional[str] = None,
column: Optional[str] = None,
schema_sample_size: int = 1,
) -> DataChain
Explodes a column containing JSON objects (dict or str DataChain type) into individual columns based on the schema of the JSON. Schema is inferred from the first row of the column.
Parameters:
-
col
(str
) –the name of the column containing JSON to be exploded.
-
model_name
(Optional[str]
, default:None
) –optional generated model name. By default generates the name automatically.
-
column
(Optional[str]
, default:None
) –optional generated column name. By default generates the name automatically.
-
schema_sample_size
(int
, default:1
) –the number of rows to use for inferring the schema of the JSON (in case some fields are optional and it's not enough to analyze a single row).
Returns:
-
DataChain
(DataChain
) –A new DataChain instance with the new set of columns.
Source code in datachain/lib/dc/datachain.py
file_diff
file_diff(
other: DataChain,
on: str = "file",
right_on: Optional[str] = None,
added: bool = True,
modified: bool = True,
deleted: bool = False,
same: bool = False,
status_col: Optional[str] = None,
) -> DataChain
Calculate differences between two chains containing files.
This method is specifically designed for file chains. It uses file source
and path
to match files, and file version
and etag
to detect changes.
Parameters:
-
other
(DataChain
) –Chain to compare against.
-
on
(str
, default:'file'
) –File column name in this chain. Default is "file".
-
right_on
(Optional[str]
, default:None
) –File column name in the other chain. Defaults to
on
. -
added
(bool
, default:True
) –Include files that exist in this chain but not in the other.
-
deleted
(bool
, default:False
) –Include files that exist only in the other chain.
-
modified
(bool
, default:True
) –Include files that exist in both but have different versions/etags.
-
same
(bool
, default:False
) –Include files that are identical in both chains.
-
status_col
(str
, default:None
) –Name for the status column showing differences (A=added, D=deleted, M=modified, S=same).
Default behavior: By default, includes only new files (added=True and modified=True). This is useful for incremental processing.
Example
Source code in datachain/lib/dc/datachain.py
1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 |
|
filter
filter(*args: Any) -> Self
Filter the chain according to conditions.
Example
Basic usage with built-in operators
Using glob to match patterns
Using in to match lists
Using datachain.func
Combining filters with "or"
Combining filters with "and"
Combining filters with "not"
Source code in datachain/lib/dc/datachain.py
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 |
|
gen
gen(
func: Optional[Union[Callable, Generator]] = None,
params: Union[None, str, Sequence[str]] = None,
output: OutputType = None,
**signal_map
) -> Self
Apply a function to each row to create new rows (with potentially new signals). The function needs to return a new objects for each of the new rows. It returns a chain itself with new signals.
Input-output relationship: 1:N
This method is similar to map()
, uses the same list of parameters, but with
one key differences: It produces a sequence of rows for each input row (like
extracting multiple file records from a single tar file or bounding boxes from a
single image file).
Example
Source code in datachain/lib/dc/datachain.py
group_by
group_by(
*,
partition_by: Optional[
Union[str, Func, Sequence[Union[str, Func]]]
] = None,
**kwargs: Func
) -> Self
Group rows by specified set of signals and return new signals with aggregated values.
The supported functions
count(), sum(), avg(), min(), max(), any_value(), collect(), concat()
Example
Using complex signals:
Source code in datachain/lib/dc/datachain.py
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 |
|
limit
limit(n: int) -> Self
Return the first n
rows of the chain.
If the chain is unordered, which rows are returned is undefined.
If the chain has less than n
rows, the whole chain is returned.
Parameters:
-
n
(int
) –Number of rows to return.
Source code in datachain/lib/dc/datachain.py
map
map(
func: Optional[Callable] = None,
params: Union[None, str, Sequence[str]] = None,
output: OutputType = None,
**signal_map
) -> Self
Apply a function to each row to create new signals. The function should return a new object for each row. It returns a chain itself with new signals.
Input-output relationship: 1:1
Parameters:
-
func
–Function applied to each row.
-
params
–List of column names used as input for the function. Default is taken from function signature.
-
output
–Dictionary defining new signals and their corresponding types. Default type is taken from function signature. Default can be also taken from kwargs - **signal_map (see below). If signal name is defined using signal_map (see below) only a single type value can be used.
-
**signal_map
–kwargs can be used to define
func
together with it's return signal name in format ofmap(my_sign=my_func)
. This helps define signal names and function in a nicer way.
Example
Using signal_map and single type in output:
Using func and output as a map:
Source code in datachain/lib/dc/datachain.py
max
max(col: str) -> StandardType
Compute the maximum of a column.
Parameters:
-
col
(str
) –The column to compute the maximum for.
Returns:
-
StandardType
–The maximum value in the column.
Source code in datachain/lib/dc/datachain.py
merge
merge(
right_ds: DataChain,
on: Union[MergeColType, Sequence[MergeColType]],
right_on: Optional[
Union[MergeColType, Sequence[MergeColType]]
] = None,
inner=False,
full=False,
rname="right_",
) -> Self
Merge two chains based on the specified criteria.
Parameters:
-
right_ds
(DataChain
) –Chain to join with.
-
on
(Union[MergeColType, Sequence[MergeColType]]
) –Predicate ("column.name", C("column.name"), or Func) or list of Predicates to join on. If both chains have the same predicates then this predicate is enough for the join. Otherwise,
right_on
parameter has to specify the predicates for the other chain. -
right_on
(Optional[Union[MergeColType, Sequence[MergeColType]]]
, default:None
) –Optional predicate or list of Predicates for the
right_ds
to join. -
inner
(bool
, default:False
) –Whether to run inner join or outer join.
-
full
(bool
, default:False
) –Whether to run full outer join.
-
rname
(str
, default:'right_'
) –Name prefix for conflicting signal names.
Examples:
imgs.merge(captions,
on=func.path.file_stem(imgs.c("file.path")),
right_on=func.path.file_stem(captions.c("file.path"))
)
Source code in datachain/lib/dc/datachain.py
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 |
|
min
min(col: str) -> StandardType
Compute the minimum of a column.
Parameters:
-
col
(str
) –The column to compute the minimum for.
Returns:
-
StandardType
–The minimum value in the column.
Source code in datachain/lib/dc/datachain.py
mutate
Create new signals based on existing signals.
This method cannot modify existing columns. If you need to modify an
existing column, use a different name for the new column and then use
select()
to choose which columns to keep.
This method is vectorized and more efficient compared to map(), and it does not extract or download any data from the internal database. However, it can only utilize predefined built-in functions and their combinations.
The supported functions
Numerical: +, -, *, /, rand(), avg(), count(), func(), greatest(), least(), max(), min(), sum() String: length(), split(), replace(), regexp_replace() Filename: name(), parent(), file_stem(), file_ext() Array: length(), sip_hash_64(), euclidean_distance(), cosine_distance() Window: row_number(), rank(), dense_rank(), first()
Example:
dc.mutate(
area=Column("image.height") * Column("image.width"),
extension=file_ext(Column("file.path")),
dist=cosine_distance(embedding_text, embedding_image)
)
Window function example:
window = func.window(partition_by="file.parent", order_by="file.size")
dc.mutate(
row_number=func.row_number().over(window),
)
This method can be also used to rename signals. If the Column("name") provided as value for the new signal - the old column will be dropped. Otherwise a new column is created.
Example:
Source code in datachain/lib/dc/datachain.py
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 |
|
offset
offset(offset: int) -> Self
Return the results starting with the offset row.
If the chain is unordered, which rows are skipped in undefined.
If the chain has less than offset
rows, the result is an empty chain.
Parameters:
-
offset
(int
) –Number of rows to skip.
Source code in datachain/lib/dc/datachain.py
order_by
order_by(*args, descending: bool = False) -> Self
Orders by specified set of columns.
Parameters:
-
descending
(bool
, default:False
) –Whether to sort in descending order or not.
Note
Order is not guaranteed when steps are added after an order_by
statement.
I.e. when using read_dataset
an order_by
statement should be used if
the order of the records in the chain is important.
Using order_by
directly before limit
, to_list
and similar methods
will give expected results.
See https://github.com/iterative/datachain/issues/477 for further details.
Source code in datachain/lib/dc/datachain.py
parse_tabular
parse_tabular(
output: OutputType = None,
column: str = "",
model_name: str = "",
source: bool = True,
nrows: Optional[int] = None,
**kwargs
) -> Self
Generate chain from list of tabular files.
Parameters:
-
output
–Dictionary or feature class defining column names and their corresponding types. List of column names is also accepted, in which case types will be inferred.
-
column
–Generated column name.
-
model_name
–Generated model name.
-
source
–Whether to include info about the source file.
-
nrows
–Optional row limit.
-
kwargs
–Parameters to pass to pyarrow.dataset.dataset.
Example
Reading a json lines file:
import datachain as dc
chain = dc.read_storage("s3://mybucket/file.jsonl")
chain = chain.parse_tabular(format="json")
Reading a filtered list of files as a dataset:
Source code in datachain/lib/dc/datachain.py
1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 |
|
persist
Saves temporary chain that will be removed after the process ends. Temporary datasets are useful for optimization, for example when we have multiple chains starting with identical sub-chain. We can then persist that common chain and use it to calculate other chains, to avoid re-calculation every time. It returns the chain itself.
Source code in datachain/lib/dc/datachain.py
print_schema
reset_settings
reset_settings(settings: Optional[Settings] = None) -> Self
sample
sample(n: int) -> Self
Return a random sample from the chain.
Parameters:
-
n
(int
) –Number of samples to draw.
Note
Samples are not deterministic, and streamed/paginated queries or multiple workers will draw samples with replacement.
Source code in datachain/lib/dc/datachain.py
save
save(
name: str,
version: Optional[str] = None,
description: Optional[str] = None,
attrs: Optional[list[str]] = None,
update_version: Optional[str] = "patch",
**kwargs
) -> DataChain
Save to a Dataset. It returns the chain itself.
Parameters:
-
name
–dataset name. It can be full name consisting of namespace and project, but it can also be just a regular dataset name in which case we are taking namespace and project from settings, if they are defined there, or default ones instead.
-
version
–version of a dataset. If version is not specified and dataset already exists, version patch increment will happen e.g 1.2.1 -> 1.2.2.
-
description
–description of a dataset.
-
attrs
–attributes of a dataset. They can be without value, e.g "NLP", or with a value, e.g "location=US".
-
update_version
(Optional[str]
, default:'patch'
) –which part of the dataset version to automatically increase. Available values:
major
,minor
orpatch
. Default ispatch
.
Source code in datachain/lib/dc/datachain.py
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 |
|
select
Select only a specified set of signals.
Source code in datachain/lib/dc/datachain.py
select_except
select_except(*args: str) -> Self
Select all the signals expect the specified signals.
Source code in datachain/lib/dc/datachain.py
settings
settings(
cache=None,
parallel=None,
workers=None,
min_task_size=None,
prefetch: Optional[int] = None,
sys: Optional[bool] = None,
namespace: Optional[str] = None,
project: Optional[str] = None,
) -> Self
Change settings for chain.
This function changes specified settings without changing not specified ones. It returns chain, so, it can be chained later with next operation.
Parameters:
-
cache
–data caching (default=False)
-
parallel
–number of thread for processors. True is a special value to enable all available CPUs (default=1)
-
workers
–number of distributed workers. Only for Studio mode. (default=1)
-
min_task_size
–minimum number of tasks (default=1)
-
prefetch
(Optional[int]
, default:None
) –number of workers to use for downloading files in advance. This is enabled by default and uses 2 workers. To disable prefetching, set it to 0.
-
namespace
(Optional[str]
, default:None
) –namespace name.
-
project
(Optional[str]
, default:None
) –project name.
Example
Source code in datachain/lib/dc/datachain.py
setup
Setup variables to pass to UDF functions.
Use before running map/gen/agg/batch_map to save an object and pass it as an argument to the UDF.
The value must be a callable (a lambda: <value>
syntax can be used to quickly
create one) that returns the object to be passed to the UDF. It is evaluated
lazily when UDF is running, in case of multiple machines the callable is run on
a worker machine.
Example
import anthropic
from anthropic.types import Message
import datachain as dc
(
dc.read_storage(DATA, type="text")
.settings(parallel=4, cache=True)
# Setup Anthropic client and pass it to the UDF below automatically
# The value is callable (see the note above)
.setup(client=lambda: anthropic.Anthropic(api_key=API_KEY))
.map(
claude=lambda client, file: client.messages.create(
model=MODEL,
system=PROMPT,
messages=[{"role": "user", "content": file.get_value()}],
),
output=Message,
)
)
Source code in datachain/lib/dc/datachain.py
show
show(
limit: int = 20,
flatten: bool = False,
transpose: bool = False,
truncate: bool = True,
include_hidden: bool = False,
) -> None
Show a preview of the chain results.
Parameters:
-
limit
(int
, default:20
) –How many rows to show.
-
flatten
(bool
, default:False
) –Whether to use a multiindex or flatten column names.
-
transpose
(bool
, default:False
) –Whether to transpose rows and columns.
-
truncate
(bool
, default:True
) –Whether or not to truncate the contents of columns.
-
include_hidden
(bool
, default:False
) –Whether to include hidden columns.
Source code in datachain/lib/dc/datachain.py
shuffle
subtract
subtract(
other: DataChain,
on: Optional[Union[str, Sequence[str]]] = None,
right_on: Optional[Union[str, Sequence[str]]] = None,
) -> Self
Remove rows that appear in another chain.
Parameters:
-
other
(DataChain
) –chain whose rows will be removed from
self
-
on
(Optional[Union[str, Sequence[str]]]
, default:None
) –columns to consider for determining row equality in
self
. If unspecified, defaults to all common columns betweenself
andother
. -
right_on
(Optional[Union[str, Sequence[str]]]
, default:None
) –columns to consider for determining row equality in
other
. If unspecified, defaults to the same values ason
.
Source code in datachain/lib/dc/datachain.py
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 |
|
sum
sum(col: str) -> StandardType
Compute the sum of a column.
Parameters:
-
col
(str
) –The column to compute the sum for.
Returns:
-
StandardType
–The sum of the column values.
Source code in datachain/lib/dc/datachain.py
to_columnar_data_with_names
to_columnar_data_with_names(
chunk_size: int = DEFAULT_PARQUET_CHUNK_SIZE,
) -> tuple[list[str], Iterator[list[list[Any]]]]
Returns column names and the results as an iterator that provides chunks, with each chunk containing a list of columns, where each column contains a list of the row values for that column in that chunk. Useful for columnar data formats, such as parquet or other OLAP databases.
Source code in datachain/lib/dc/datachain.py
to_csv
to_csv(
path: Union[str, PathLike[str]],
delimiter: str = ",",
fs_kwargs: Optional[dict[str, Any]] = None,
**kwargs
) -> None
Save chain to a csv (comma-separated values) file.
Parameters:
-
path
–Path to save the file. This supports local paths as well as remote paths, such as s3:// or hf:// with fsspec.
-
delimiter
–Delimiter to use for the resulting file.
-
fs_kwargs
–Optional kwargs to pass to the fsspec filesystem, used only for write, for fsspec-type URLs, such as s3:// or hf:// when provided as the destination path.
Source code in datachain/lib/dc/datachain.py
to_iter
Yields rows of values, optionally limited to the specified columns.
Parameters:
-
*cols
(str
, default:()
) –Limit to the specified columns. By default, all columns are selected.
Yields:
Example
Iterating over all rows:
DataChain is iterable and can be used in a for loop directly which is
equivalent to ds.to_iter()
:
Iterating over all rows with selected columns:
Iterating over a single column:
Source code in datachain/lib/dc/datachain.py
to_json
to_json(
path: Union[str, PathLike[str]],
fs_kwargs: Optional[dict[str, Any]] = None,
include_outer_list: bool = True,
) -> None
Save chain to a JSON file.
Parameters:
-
path
–Path to save the file. This supports local paths as well as remote paths, such as s3:// or hf:// with fsspec.
-
fs_kwargs
–Optional kwargs to pass to the fsspec filesystem, used only for write, for fsspec-type URLs, such as s3:// or hf:// when provided as the destination path.
-
include_outer_list
–Sets whether to include an outer list for all rows. Setting this to True makes the file valid JSON, while False instead writes in the JSON lines format.
Source code in datachain/lib/dc/datachain.py
to_jsonl
Save chain to a JSON lines file.
Parameters:
-
path
–Path to save the file. This supports local paths as well as remote paths, such as s3:// or hf:// with fsspec.
-
fs_kwargs
–Optional kwargs to pass to the fsspec filesystem, used only for write, for fsspec-type URLs, such as s3:// or hf:// when provided as the destination path.
Source code in datachain/lib/dc/datachain.py
to_list
Returns a list of rows of values, optionally limited to the specified columns.
Parameters:
-
*cols
(str
, default:()
) –Limit to the specified columns. By default, all columns are selected.
Returns:
-
list[tuple[DataValue, ...]]
–list[tuple[DataType, ...]]: Returns a list of tuples of items for each row.
Example
Getting all rows as a list:
Getting all rows with selected columns as a list:
Getting a single column as a list:
Source code in datachain/lib/dc/datachain.py
to_pandas
Return a pandas DataFrame from the chain.
Parameters:
-
flatten
(bool
, default:False
) –Whether to use a multiindex or flatten column names.
-
include_hidden
(bool
, default:True
) –Whether to include hidden columns.
Returns:
-
DataFrame
–pd.DataFrame: A pandas DataFrame representation of the chain.
Source code in datachain/lib/dc/datachain.py
to_parquet
to_parquet(
path: Union[str, PathLike[str], BinaryIO],
partition_cols: Optional[Sequence[str]] = None,
chunk_size: int = DEFAULT_PARQUET_CHUNK_SIZE,
fs_kwargs: Optional[dict[str, Any]] = None,
**kwargs
) -> None
Save chain to parquet file with SignalSchema metadata.
Parameters:
-
path
–Path or a file-like binary object to save the file. This supports local paths as well as remote paths, such as s3:// or hf:// with fsspec.
-
partition_cols
–Column names by which to partition the dataset.
-
chunk_size
–The chunk size of results to read and convert to columnar data, to avoid running out of memory.
-
fs_kwargs
–Optional kwargs to pass to the fsspec filesystem, used only for write, for fsspec-type URLs, such as s3:// or hf:// when provided as the destination path.
Source code in datachain/lib/dc/datachain.py
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 |
|
to_pytorch
to_pytorch(
transform=None,
tokenizer=None,
tokenizer_kwargs=None,
num_samples=0,
remove_prefetched: bool = False,
)
Convert to pytorch dataset format.
Parameters:
-
transform
(Transform
, default:None
) –Torchvision transforms to apply to the dataset.
-
tokenizer
(Callable
, default:None
) –Tokenizer to use to tokenize text values.
-
tokenizer_kwargs
(dict
, default:None
) –Additional kwargs to pass when calling tokenizer.
-
num_samples
(int
, default:0
) –Number of random samples to draw for each epoch. This argument is ignored if
num_samples=0
(the default). -
remove_prefetched
(bool
, default:False
) –Whether to remove prefetched files after reading.
Example
Source code in datachain/lib/dc/datachain.py
to_records
Convert every row to a dictionary.
Source code in datachain/lib/dc/datachain.py
to_storage
to_storage(
output: Union[str, PathLike[str]],
signal: str = "file",
placement: ExportPlacement = "fullpath",
link_type: Literal["copy", "symlink"] = "copy",
num_threads: Optional[int] = EXPORT_FILES_MAX_THREADS,
anon: bool = False,
client_config: Optional[dict] = None,
) -> None
Export files from a specified signal to a directory. Files can be exported to a local or cloud directory.
Parameters:
-
output
(Union[str, PathLike[str]]
) –Path to the target directory for exporting files.
-
signal
(str
, default:'file'
) –Name of the signal to export files from.
-
placement
(ExportPlacement
, default:'fullpath'
) –The method to use for naming exported files. The possible values are: "filename", "etag", "fullpath", and "checksum".
-
link_type
(Literal['copy', 'symlink']
, default:'copy'
) –Method to use for exporting files. Falls back to
'copy'
if symlinking fails. -
num_threads
–number of threads to use for exporting files. By default it uses 5 threads.
-
anon
(bool
, default:False
) –If true, we will treat cloud bucket as public one
-
client_config
(Optional[dict]
, default:None
) –Optional configuration for the destination storage client
Example
Cross cloud transfer
Source code in datachain/lib/dc/datachain.py
to_values
Returns a flat list of values from a single column.
Parameters:
-
col
(str
) –The name of the column to extract values from.
Returns:
-
list[DataValue]
–list[DataValue]: Returns a flat list of values from the specified column.
Example
Getting all values from a single column:
Getting all file sizes:
Source code in datachain/lib/dc/datachain.py
union
Return the set union of the two datasets.
Parameters:
-
other
(Self
) –chain whose rows will be added to
self
.
Source code in datachain/lib/dc/datachain.py
DataChainError
Bases: Exception
Session
Session(
name="",
catalog: Optional[Catalog] = None,
client_config: Optional[dict] = None,
in_memory: bool = False,
)
Session is a context that keeps track of temporary DataChain datasets for a proper cleanup. By default, a global session is created.
Temporary or ephemeral datasets are the ones created without specified name. They are useful for optimization purposes and should be automatically removed.
Temp dataset has specific name format
"session_
The
Temp dataset examples
session_myname_624b41_48e8b4 session_4b962d_2a5dff
Parameters:
name (str): The name of the session. Only latters and numbers are supported. It can be empty. catalog (Catalog): Catalog object.
Source code in datachain/query/session.py
get
classmethod
get(
session: Optional[Session] = None,
catalog: Optional[Catalog] = None,
client_config: Optional[dict] = None,
in_memory: bool = False,
) -> Session
Creates a Session() object from a catalog.
Parameters:
-
session
(Session
, default:None
) –Optional Session(). If not provided a new session will be created. It's needed mostly for simple API purposes.
-
catalog
(Catalog
, default:None
) –Optional catalog. By default, a new catalog is created.