Skip to main content

A thin wrapper over np.ndarray to provide an intuitive interface for attaching pydantic models as metadata to arrays.

Project description

dantArrays: Enhanced NumPy Arrays with Rich, Computed Metadata


Overview

dantArrays extends standard NumPy arrays by embedding rich, computed metadata directly into array slices, rows, or columns. This integration allows you to keep data tightly coupled with its descriptive context, computed metrics, or dynamic annotations—without losing NumPy's efficiency and versatility.


Key Features

  • Rich Metadata Integration: Attach structured metadata (using Pydantic models) to slices of NumPy arrays.
  • Automatic Computations: Define metadata fields computed directly from array data.
  • Data Safety: Safe mechanisms to access and modify underlying array data without corrupting computed metadata.
  • Flexibility: Easily update array slices or metadata, automatically recalculating dependent computed fields.
  • Usability: Clear, Pythonic API for both simple and complex data manipulation tasks.

Installation

pip install dantarrays

Quickstart Example

Here's how easily you can add metadata to your arrays:

import numpy as np
from pydantic import BaseModel
from dantarrays import DantArray, mean_value_field

class StockMetadata(BaseModel):
    symbol: str
    mean_price: float = mean_value_field()

price_data = np.array([
    [100, 101, 102],
    [50, 49, 51],
])

stocks = DantArray(data=price_data, metadata_class=StockMetadata, major_axis=0)

stocks.update_metadata(0, symbol="AAPL")
stocks.update_metadata(1, symbol="MSFT")

print(stocks.meta(0).mean_price)  # Automatically computed mean price
# Output: 101.0

Usage

Defining Metadata Models

Use Pydantic models to define structured metadata:

from pydantic import BaseModel
from dantarrays import max_value_field, mean_value_field

class ExperimentMetadata(BaseModel):
    experiment_id: str
    max_measurement: float = max_value_field()
    avg_measurement: float = mean_value_field()

Creating a DantArray

import numpy as np
from dantarrays import DantArray

data = np.random.rand(5, 10)
experiments = DantArray(data=data, metadata_class=ExperimentMetadata, major_axis=0)

Updating Metadata

experiments.update_metadata(0, experiment_id="EXP001")

Accessing Metadata

metadata = experiments.get_metadata(0)
print(metadata.max_measurement)

Using the .meta() API for Convenient Field Access

The .meta() method provides ergonomic, attribute-style access to metadata fields:

experiments.meta(0).experiment_id = "EXP002"
print(experiments.meta(0).experiment_id)
# Output: EXP002

You can also update multiple fields conveniently:

experiments.meta(0).update(experiment_id="EXP003", avg_measurement=0.75)

Editing Data Safely

with experiments.edit_data() as data:
    data[0, :] = np.random.rand(10)

Immutable Updates

updated_experiments = experiments.with_updated_slice(0, np.zeros(10))

Advanced Examples

Batch Metadata Creation

indices = [0, 1, 2]
experiments.batch_create(indices, experiment_id="default")

Computed Fields Based on Data

Create a metadata field dynamically computed from the data slice:

from dantarrays import data_based_field

class ImageMetadata(BaseModel):
    brightness: float = data_based_field(lambda slice: float(np.mean(slice)))

Accessing Full Metadata

for idx, meta in experiments.get_existing_metadata():
    print(f"Experiment {meta.experiment_id} avg: {meta.avg_measurement}")

Data Validation and Safety

Direct access to the internal data array triggers warnings, ensuring safe data manipulation:

experiments._data_unsafe  # Warns about unsafe access

Contextual Computations

Computed fields have access to context about their array slice:

from dantarrays import ComputedFieldContext

class CustomComputation:
    def __call__(self, ctx: ComputedFieldContext):
        return ctx.size * np.mean(ctx.get_slice())

API Reference

DantArray

  • .update_metadata(idx, **kwargs): Update metadata fields.
  • .get_metadata(idx): Retrieve metadata.
  • .meta(idx): Convenient, attribute-style metadata accessor.
  • .batch_create(indices, **kwargs): Batch create metadata entries.
  • .with_updated_data(new_data): Immutable data update.
  • .apply_with_metadata(func): Apply function to array slices and metadata.
  • .refresh_computed_fields(): Refresh computed fields after data changes.

Use Cases

  • Financial time-series analysis
  • Image datasets with annotations
  • Scientific experiment tracking
  • Feature metadata management in machine learning

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

dantarrays-0.0.2.tar.gz (27.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

dantarrays-0.0.2-py3-none-any.whl (11.3 kB view details)

Uploaded Python 3

File details

Details for the file dantarrays-0.0.2.tar.gz.

File metadata

  • Download URL: dantarrays-0.0.2.tar.gz
  • Upload date:
  • Size: 27.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.5.26

File hashes

Hashes for dantarrays-0.0.2.tar.gz
Algorithm Hash digest
SHA256 4708d6888723bc83d0d5f411ce48ed94ee89d94db0d2cd688e2eb57b741c197c
MD5 e57a9f3b4be5f1c82d6398df71763f4d
BLAKE2b-256 568e28427c3f9fc7fc465e6f9e90c9d5662875a38eb1b48c650aa8aadd00614b

See more details on using hashes here.

File details

Details for the file dantarrays-0.0.2-py3-none-any.whl.

File metadata

  • Download URL: dantarrays-0.0.2-py3-none-any.whl
  • Upload date:
  • Size: 11.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.5.26

File hashes

Hashes for dantarrays-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 d47f662e6cd07d619578fc4f10a0464df72ed3901c23ff0357d21b62ab0f37e9
MD5 f7d53f6b0657ac021a2e7c74d396fc8f
BLAKE2b-256 166efe6ed917c3c00f3dbedb2b11f1f5765f8fd3465a1610376ea490653ed4a4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page