Describe your database
Build a Database from your tables by declaring each table's primary key and the foreign keys that connect the tables. This lets an estimator find the related rows for each sample in X.
Tables, primary keys and relationships
Start with two pandas DataFrames. Each row of customers describes one customer, so customer_id is unique there. A customer can place several orders, so orders has its own primary key, order_id, and repeats customer_id as a foreign key.
import pandas as pd
from sklink import Database
customers = pd.DataFrame(
{
"customer_id": [1, 2, 3, 4],
"country": ["CO", "PE", "CO", "MX"],
"zip_code": [11001, 15001, 11001, 1000],
}
)
orders = pd.DataFrame(
{
"order_id": [10, 11, 12, 13, 14, 15],
"customer_id": [1, 1, 2, 3, 3, 3],
"type": ["express", "standard", "express", "pickup", "express", "express"],
"amount": [120.0, 35.5, 80.0, 15.0, 210.0, 99.9],
"internal_note": ["ok", "ok", "late", "ok", "ok", "late"],
}
)
db = Database(
tables={"customers": customers, "orders": orders},
primary_keys={"customers": "customer_id", "orders": "order_id"},
relationships=[("orders.customer_id", "customers.customer_id")],
)
print(db.table_names, db.n_rows("orders"))('customers', 'orders') 6tablesmaps a name to a table. pandas, Polars and PyArrow tables work, as do a mapping of column names to 1-D arrays and the path of a Parquet file.primary_keysgives each table's key column, a list of columns for a composite key, orNonefor a table without a key.relationshipslists the foreign keys with the child first. In("orders.customer_id", "customers.customer_id"), the order points to the customer. The first two orders share customer 1, and customer 4 has no orders. Both cases are valid.
The database checks keys when it is built. Duplicate primary keys and foreign keys without a parent row are errors by default.
Check what was inferred
describe() returns a plain dictionary with the row count, key, time column and semantic type of every column. To see the same as a diagram, with the number of child rows per parent, use SchemaDisplay.from_database(db) from sklink.plotting.
info = db.describe()
for table, details in info["tables"].items():
print(table, details["columns"])customers {'customer_id': 'id', 'country': 'categorical', 'zip_code': 'numeric'}
orders {'order_id': 'id', 'customer_id': 'id', 'type': 'categorical', 'amount': 'numeric', 'internal_note': 'categorical'}describe() reports how the library will treat each column. It inferred zip_code as numeric from its integers. Those integers identify places, so give the column a categorical type before building features. The section Fix types and exclude columns below shows how.
Check the relationships
describe(statistics=True) also counts the children of every parent row. It shows customers without orders, orphan rows and how skewed a relationship is, before you build features on it.
statistics = db.describe(statistics=True)["relationships"][0]["statistics"]
print(statistics["mean"], statistics["max"], statistics["n_parents_without_children"])
print(statistics["children_per_parent"])1.5 3 1
[[0, 1], [1, 1], [2, 1], [3, 1]]children_per_parent lists pairs of a number of children and how many parents have that many: here one customer has no orders and one has three.
Read a table back
table returns a copy of a table, in the format you ask for with output. Rows come sorted by primary key, whatever order the input had.
print(db.table("orders", output="pandas").head(3)) order_id customer_id type amount internal_note
0 10 1 express 120.0 ok
1 11 1 standard 35.5 ok
2 12 2 express 80.0 lateFix types and exclude columns
column_types overrides inference, and exclude keeps columns out of feature and split search. Here an internal note could be written after the event you want to predict, so the example excludes it.
db = Database(
tables={"customers": customers, "orders": orders},
primary_keys={"customers": "customer_id", "orders": "order_id"},
relationships=[("orders.customer_id", "customers.customer_id")],
column_types={"customers": {"zip_code": "categorical"}},
exclude={"orders": ["internal_note"]},
)
print(db.describe()["tables"]["customers"]["columns"]){'customer_id': 'id', 'country': 'categorical', 'zip_code': 'categorical'}The semantic types are numeric, categorical, boolean, datetime, text and id. Keys are always id and are never aggregated as numbers. Free text, such as reviews or descriptions, is inferred as text and feeds no feature: a string column whose values average 30 characters or more and are nearly all distinct (at least 100 distinct values and 90% of the present ones), where each value would be a category of about one row. Declare such a column categorical in column_types to aggregate it anyway, and declare the type of any column near those limits, so that a model fitted on one snapshot of the data can be used on the next.
Orphan rows
An order is an orphan if its foreign key names a customer missing from customers. A partial export can produce this situation. The default validation catches it when you construct the database.
from sklink.exceptions import IntegrityError
orders_with_orphan = pd.concat(
[
orders,
pd.DataFrame(
{
"order_id": [16],
"customer_id": [99],
"type": ["pickup"],
"amount": [5.0],
"internal_note": ["ok"],
}
),
]
)
try:
Database(
tables={"customers": customers, "orders": orders_with_orphan},
primary_keys={"customers": "customer_id", "orders": "order_id"},
relationships=[("orders.customer_id", "customers.customer_id")],
)
except IntegrityError as error:
print(error)Relationship 'orders.customer_id->customers' has 1 rows in 'orders' whose key has no matching row in 'customers'. Pass orphans='ignore' to keep them.Use orphans="warn" to keep those orders and see a warning, or orphans="ignore" to keep them without a warning. Kept orphan rows never feed a customer's features, because no customer leads to them.
Validation cost
validate="full" (the default) scans the data for duplicate keys and orphans. For large tables you trust, validate="schema" and validate="none" skip the scans of the data and still check the declarations, such as that every key column exists.
Other table formats
You can mix supported formats in one database. This example passes a Polars DataFrame for customers and a Parquet path for orders. Install the polars and pyarrow extras to run it. See optional dependencies.
from pathlib import Path
from tempfile import TemporaryDirectory
import polars as pl
with TemporaryDirectory() as folder:
order_file = Path(folder) / "orders.parquet"
orders.to_parquet(order_file)
db_mixed = Database(
tables={"customers": pl.from_pandas(customers), "orders": order_file},
primary_keys={"customers": "customer_id", "orders": "order_id"},
relationships=[("orders.customer_id", "customers.customer_id")],
)
print(db_mixed.n_rows("orders"))6Save and reload the schema
The schema is the data-free part of the database: tables, columns, types, keys and relationships. It round-trips through JSON, so you can keep it in your repository and rebuild the database from a folder of Parquet files, one file per table.
with TemporaryDirectory() as folder:
shop = Path(folder)
customers.to_parquet(shop / "customers.parquet")
orders.to_parquet(shop / "orders.parquet")
schema_file = shop / "schema.json"
schema_file.write_text(db.schema.to_json(), encoding="utf-8")
reloaded = Database.from_parquet_dir(shop, schema=schema_file)
print(reloaded.table_names)('customers', 'orders')Composite keys and several links to the same table
A composite key is a list of columns, and a relationship over it lists the columns in the same order on both sides.
stores = pd.DataFrame({"store": [1, 2]})
days = pd.DataFrame({"store": [1, 1, 2], "day": [1, 2, 1], "visits": [30, 42, 18]})
sales = pd.DataFrame(
{
"sale_id": [1, 2, 3, 4],
"store": [1, 1, 2, 2],
"day": [1, 2, 1, 1],
"total": [9.5, 3.0, 7.25, 1.0],
}
)
db_stores = Database(
tables={"stores": stores, "days": days, "sales": sales},
primary_keys={"stores": "store", "days": ["store", "day"], "sales": "sale_id"},
relationships=[
("days.store", "stores.store"),
(("sales.store", "sales.day"), ("days.store", "days.day")),
],
)
print([relationship.name for relationship in db_stores.schema.relationships])['days.store->stores', 'sales.store+day->days']When two foreign keys of a table point at the same parent, such as the sender and the receiver of a message, name them with Relationship. Canonical names then show the relationship in angle brackets, such as count(<sent>).
from sklink import Relationship
users = pd.DataFrame({"user_id": [1, 2]})
messages = pd.DataFrame(
{
"message_id": [1, 2, 3],
"sender": [1, 2, 1],
"receiver": [2, 1, 2],
"length": [30, 12, 54],
}
)
db_messages = Database(
tables={"users": users, "messages": messages},
primary_keys={"users": "user_id", "messages": "message_id"},
relationships=[
Relationship("messages.sender", "users.user_id", name="sent"),
Relationship("messages.receiver", "users.user_id", name="received"),
],
)
print([relationship.name for relationship in db_messages.schema.relationships])['sent', 'received']Replace the data, keep the declarations
A database is immutable. with_tables returns a new database with the same keys, types and relationships. This example replaces orders with the four rows whose amount exceeds 50 and keeps all four customers.
large_orders = db.with_tables(orders=orders[orders["amount"] > 50])
print(large_orders.n_rows("orders"))4Parameters at a glance
| Parameter | Default | What it does |
|---|---|---|
tables | required | Name to table: pandas, Polars, PyArrow, a dict of arrays or a Parquet path |
primary_keys | required | Key column, list of columns, or None per table |
relationships | () | Foreign keys, child first, as tuples or Relationship objects |
time_columns | None | Datetime column per table for temporal mode |
column_types | None | Override inferred semantic types per table and column |
exclude | None | Columns that never feed a feature or a split |
orphans | "error" | "error", "warn" or "ignore" foreign keys without a parent |
validate | "full" | "full", "schema" or "none" |
Next: turn your own tables into X and y, then build relational features or fit a relational decision tree.