This is the development version.
Skip to content

Loading relational data ​

Load each source table into a Database, then build X with one row for each prediction you want to make. In these recipes, X holds customer IDs and the database links each customer to their support tickets. For help with keys and relationships, see Describe your database.

I haveStart hereExtra packages
CSV filesCSVpandas
Tables in SQLSQLpandas
NumPy arraysNumPyNone
One Parquet file per tableParquetpandas and pyarrow to run the example
Polars DataFramesPolarspolars

Install the packages for your recipe in the same environment as scikit-link.

Example tables ​

Run this setup once. The examples share the same customer IDs, ticket IDs and relationship. The database uses each table's primary key to identify its rows. The relationship pairs tickets.customer_id with the primary key in customers.

python
from sklink import Database

customers = {"customer_id": [1, 2, 3], "plan": ["free", "pro", "free"]}
tickets = {
    "ticket_id": [1, 2, 3, 4],
    "customer_id": [1, 1, 3, 3],
    "priority": ["high", "low", "low", "high"],
}
primary_keys = {"customers": "customer_id", "tickets": "ticket_id"}
relationships = [("tickets.customer_id", "customers.customer_id")]

From CSV files ​

If you have files already, start at pd.read_csv. Use the same type for keys on both sides of the relationship. For IDs with leading zeroes, use dtype={"customer_id": "string"} on both reads to keep the zeroes.

python
from pathlib import Path
from tempfile import TemporaryDirectory

import pandas as pd

with TemporaryDirectory() as folder:
    source = Path(folder)
    pd.DataFrame(customers).to_csv(source / "customers.csv", index=False)
    pd.DataFrame(tickets).to_csv(source / "tickets.csv", index=False)
    tables = {
        "customers": pd.read_csv(
            source / "customers.csv", dtype={"customer_id": "int64"}
        ),
        "tickets": pd.read_csv(
            source / "tickets.csv", dtype={"ticket_id": "int64", "customer_id": "int64"}
        ),
    }
db = Database(tables, primary_keys=primary_keys, relationships=relationships)
X = tables["customers"][["customer_id"]]
print(db.n_rows("tickets"), X.shape)
text
4 (3, 1)

From a SQL database ​

Read each table with pandas.read_sql. This example creates an in-memory SQLite database. On your own connection, query the columns and rows you need, keeping the keys that connect them.

python
import sqlite3
from contextlib import closing

import pandas as pd

with closing(sqlite3.connect(":memory:")) as connection:
    pd.DataFrame(customers).to_sql("customers", connection, index=False)
    pd.DataFrame(tickets).to_sql("tickets", connection, index=False)
    tables_sql = {
        "customers": pd.read_sql("SELECT customer_id, plan FROM customers", connection),
        "tickets": pd.read_sql(
            "SELECT ticket_id, customer_id, priority FROM tickets", connection
        ),
    }

db_sql = Database(tables_sql, primary_keys=primary_keys, relationships=relationships)
X_sql = tables_sql["customers"][["customer_id"]]
print(db_sql.table_names)
text
('customers', 'tickets')

Without pandas ​

Pass each table as a dictionary of one-dimensional NumPy arrays. In X, use a two-dimensional array and set key=0 to read the customer ID from its first column. The two output columns count tickets and sum their minutes.

python
import numpy as np
from sklink.feature_extraction import RelationalFeaturizer

db_np = Database(
    {
        "customers": {"customer_id": np.array(customers["customer_id"])},
        "tickets": {
            "ticket_id": np.array(tickets["ticket_id"]),
            "customer_id": np.array(tickets["customer_id"]),
            "minutes": np.array([12.0, 30.0, 5.0, 45.0]),
        },
    },
    primary_keys=primary_keys,
    relationships=relationships,
)
X_np = np.array(customers["customer_id"]).reshape(-1, 1)
featurizer = RelationalFeaturizer(
    db_np, entity="customers", key=0, primitives=["count", "sum"]
)
print(featurizer.fit_transform(X_np))
text
[[ 2. 42.]
 [ 0.  0.]
 [ 2. 50.]]

From a folder of Parquet files ​

Use the CSV recipe to create tables and db for this example. If you already have Parquet files and a schema, start at Database.from_parquet_dir. It reads one <table>.parquet file for each table named in the schema. In Database(tables=...), a table can also be the path of a Parquet file: scikit-link then reads it a few columns at a time, which keeps the memory low for large tables.

python
with TemporaryDirectory() as folder:
    source = Path(folder)
    for name, table in tables.items():
        table.to_parquet(source / f"{name}.parquet")
    schema_file = source / "schema.json"
    schema_file.write_text(db.schema.to_json(), encoding="utf-8")

    db_parquet = Database.from_parquet_dir(source, schema=schema_file)
    X_parquet = pd.read_parquet(source / "customers.parquet", columns=["customer_id"])
    print(db_parquet.n_rows("customers"))
text
3

From Polars ​

Pass Polars DataFrames directly to Database. A Polars DataFrame also works as X.

python
import polars as pl
from sklink.feature_extraction import RelationalFeaturizer

db_polars = Database(
    {"customers": pl.DataFrame(customers), "tickets": pl.DataFrame(tickets)},
    primary_keys=primary_keys,
    relationships=relationships,
)
X_polars = pl.DataFrame({"customer_id": customers["customer_id"]})
featurizer = RelationalFeaturizer(db_polars, entity="customers", key="customer_id")
print(featurizer.fit_transform(X_polars).shape)
text
(3, 9)

Keep extra columns in X ​

Start with X and db from the CSV recipe. Add features that are already known for each sample, such as a survey score. By default, the featurizer keeps these columns and reads their values directly from X. It leaves the key and any declared cutoff out of the feature matrix.

python
from sklink.feature_extraction import RelationalFeaturizer

X_extra = X.assign(nps_score=[9, 4, 7])
featurizer = RelationalFeaturizer(db, entity="customers", key="customer_id")
featurizer.fit(X_extra)
print(featurizer.get_feature_names_out()[:3])
text
['nps_score' 'plan' 'count(tickets)']

Released under the MIT License.