Datasets (reading and writing data)

Please see Datasets (introduction) for an introduction about interacting with datasets in Dataiku Python API

Basic usage

For starting code samples, please see Python recipes.

Typing of dataframes

Applies when reading a dataframe.

By default, the data frame is created without explicit typing. This means that we let Pandas “guess” the proper Pandas type for each column. The main advantage of this approach is that even if your dataset only contains “string” column (which is the default on a newly imported dataset) , if the column actually contains numbers, a proper numerical type will be used.

If you pass infer_with_pandas=False as option to get_dataframe(), the exact dataset types will be passed to Pandas. Note that if your dataset contains invalid values, the whole get_dataframe call will fail.

Chunked reading and writing with Pandas

When using Dataset.get_dataframe(), the whole dataset (or selected partitions) are read into a single Pandas dataframe, which must fit in RAM on the DSS server.

This is sometimes inconvenient and DSS provides a way to do this by chunks:

mydataset = Dataset("myname")

for df in mydataset.iter_dataframes(chunksize=10000):
        # df is a dataframe of at most 10K rows.

By doing this, you only need to load a few thousands of rows at a time.

Writing in a dataset can also be made by chunks of dataframes. For that, you need to obtain a writer:

inp = Dataset("input")
out = Dataset("output")

with out.get_writer() as writer:

        for df in inp.iter_dataframes():
                # Process the df dataframe ...

                # Write the processed dataframe
                writer.write_dataframe(df)

Note

When using chunked writing, you cannot set the schema for each chunk, you cannot use Dataset.write_with_schema.

Instead, you should set the schema first on the dataset object, using Dataset.write_schema_from_dataframe(first_output_dataframe)

Encoding

When dealing with both dataframes and row-by-row iteration, you must pay attention to str/unicode and encoding issues

  • DSS provides dataframes where the string content is utf-8 encoded str

  • When writing dataframes, DSS expects utf-8 encoded str

  • Per-line iterators provide string content as unicode objects

  • Per-line writers expect unicode objects.

For example, if you read from a dataframe but write row-by-row, you must decode your str into Unicode object

Sampling

All calls to iterate the dataset (get_dataframe, iter_dataframes, iter_rows and iter_tuples) take several arguments to set sampling.

Sampling lets you only retrieve a selection of the rows of the input dataset. It’s often useful when using Pandas if your dataset does not fit in RAM.

For more information about sampling methods, please see Sampling.

The sampling argument takes the following values.

random

Returns a random sample of the dataset. Additional arguments:

  • ratio=X: ratio (between 0 and 1) to select.

  • OR: limit=X: number of rows to read.

random-column

Return a column-based random sample. Additional arguments:

  • sampling_column: column to use for sampling

  • ratio=X: ratio (between 0 and 1) to select

Examples

# Get a Dataframe over the first 3K rows
dataset.get_dataframe(sampling='head', limit=3000)

# Iterate over a random 10% sample
dataset.iter_tuples(sampling='random', ratio=0.1)

# Iterate over 27% of the values of column 'user_id'
dataset.iter_tuples(sampling='random-column', sampling_column='user_id', ratio=0.27)

# Get a chunked stream of dataframes over 100K randomly selected rows
dataset.iter_dataframes(sampling='random', limit=100000)

Getting a dataset as raw bytes

In addition to retrieving a dataset as Pandas Dataframes or iterator, you can also ask DSS for a streamed export, as formatted data.

Data can be exported by DSS in various formats: CSV, Excel, Avro, …

# Read a dataset as Excel, and dump to a file, chunk by chunk
#
# Very important: you MUST use a with() statement to ensure that the stream
# returned by raw_formatted is closed

with open(target_path, "wb") as ofl:
        with dataset.raw_formatted_data(format="excel") as ifl:
                while True:
                        chunk = ifl.read(32000)
                        if len(chunk) == 0:
                                break
                        ofl.write(chunk)

Data interaction (dataikuapi variant)

This section covers reading data using the dataikuapi pacakge. We recommend that you rather use the dataiku package for reading data.

Reading data (dataikuapi variant)

The data of a dataset can be streamed with the iter_rows() method. This call returns the raw data, so that in most cases it is necessary to first get the dataset’s schema with a call to get_schema(). For example, printing the first 10 rows can be done with

columns = [column['name'] for column in dataset.get_schema()['columns']]
print(columns)
row_count = 0
for row in dataset.iter_rows():
        print(row)
        row_count = row_count + 1
        if row_count >= 10:
                break

outputs

['tube_assembly_id', 'supplier', 'quote_date', 'annual_usage', 'min_order_quantity', 'bracket_pricing', 'quantity', 'cost']
['TA-00002', 'S-0066', '2013-07-07', '0', '0', 'Yes', '1', '21.9059330191461']
['TA-00002', 'S-0066', '2013-07-07', '0', '0', 'Yes', '2', '12.3412139792904']
['TA-00002', 'S-0066', '2013-07-07', '0', '0', 'Yes', '5', '6.60182614356538']
['TA-00002', 'S-0066', '2013-07-07', '0', '0', 'Yes', '10', '4.6877695119712']
['TA-00002', 'S-0066', '2013-07-07', '0', '0', 'Yes', '25', '3.54156118026073']
['TA-00002', 'S-0066', '2013-07-07', '0', '0', 'Yes', '50', '3.22440644770007']
['TA-00002', 'S-0066', '2013-07-07', '0', '0', 'Yes', '100', '3.08252143576504']
['TA-00002', 'S-0066', '2013-07-07', '0', '0', 'Yes', '250', '2.99905966403855']
['TA-00004', 'S-0066', '2013-07-07', '0', '0', 'Yes', '1', '21.9727024365273']
['TA-00004', 'S-0066', '2013-07-07', '0', '0', 'Yes', '2', '12.4079833966715']

Reading data for a partition (dataikuapi variant)

The data of a given partition can be retrieved by passing the appropriate partition spec as parameter to iter_rows():

row_count = 0
for row in dataset.iter_rows(partitions='partition_spec1,partition_spec2'):
        print(row)
        row_count = row_count + 1
        if row_count >= 10:
                break