03 · Adding values¶
You will learn the ways to add values to a study (long tables, NumPy arrays, single values), and the safety checks that keep it consistent: unknown ids, overwrites, failed additions.
You need 02 · Units and variables, for levels and dimensions.
import numpy as np
import pandas as pd
import synaptome as syn
From a long table¶
The most common form: one row per value, with the unit ids, one column per dimension, and the values.
Units don't need the same coordinates: here s02 was weighed at weeks 0, 6 and 12, the others at 0 and
12 only.
study = syn.Study("Weight trial")
study.add_units("subject", ["s01", "s02", "s03"])
weights = pd.DataFrame(
{
"subject": ["s01", "s01", "s02", "s02", "s02", "s03", "s03"],
"time": [0, 12, 0, 6, 12, 0, 12],
"kg": [82.1, 80.4, 75.4, 74.9, 74.0, 90.2, np.nan],
}
)
study.add("weight", weights, value="kg")
study.to_df("weight")
/tmp/ipykernel_2618/2782592429.py:10: InferenceNotice: Inferred definition for 'weight': weight[time]: float @ subject. Review it with study.variables['weight'], or define the variable explicitly.
study.add("weight", weights, value="kg")
| subject | time | weight | |
|---|---|---|---|
| 0 | s01 | 0 | 82.1 |
| 1 | s01 | 12 | 80.4 |
| 2 | s02 | 0 | 75.4 |
| 3 | s02 | 6 | 74.9 |
| 4 | s02 | 12 | 74.0 |
| 5 | s03 | 0 | 90.2 |
| 6 | s03 | 12 | NaN |
value="kg" names the column holding the values when it isn't called after the variable. The missing
weight of s03 at week 12 is stored as an explicit missing value, and describe counts it:
study.describe()
| variable | level | dims | dtype | measurement_unit | units_with_values | units_at_level | values | missing | inferred | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | weight | subject | time(3) | float | None | 3 | 3 | 7 | 1 | True |
From arrays¶
Signals often come as one array per unit. Pass the unit id and the coordinates of each axis as keywords, in axis order.
t = np.linspace(0.0, 0.5, 6)
rng = np.random.default_rng(0)
for subject in ["s01", "s02", "s03"]:
study.add("erp", rng.normal(size=t.size).round(2), subject=subject, time=t)
study.to_df("erp").head()
/tmp/ipykernel_2618/3801372606.py:4: InferenceNotice: Inferred definition for 'erp': erp[time]: float @ subject. Review it with study.variables['erp'], or define the variable explicitly.
study.add("erp", rng.normal(size=t.size).round(2), subject=subject, time=t)
| subject | time | erp | |
|---|---|---|---|
| 0 | s01 | 0.0 | 0.13 |
| 1 | s01 | 0.1 | -0.13 |
| 2 | s01 | 0.2 | 0.64 |
| 3 | s01 | 0.3 | 0.10 |
| 4 | s01 | 0.4 | -0.54 |
A single value works the same way, with no coordinates:
study.add("age", 34, subject="s01")
study.add("age", 41, subject="s02")
study.to_df("age")
/tmp/ipykernel_2618/4058737912.py:1: InferenceNotice: Inferred definition for 'age': age: int @ subject. Review it with study.variables['age'], or define the variable explicitly.
study.add("age", 34, subject="s01")
| subject | age | |
|---|---|---|
| 0 | s01 | 34 |
| 1 | s02 | 41 |
Safety checks¶
Once a level has units, an id synaptome doesn't know is an error. This catches typos such as s1 for
s01:
typo = pd.DataFrame({"subject": ["s1"], "time": [6], "weight": [81.0]})
try:
study.add("weight", typo)
except KeyError as err:
print(err)
"1 row(s) refer to unknown subject units, e.g. [{'subject': 's1'}]."
When the new unit is genuine (a late recruit), say so with create_units=True:
late = pd.DataFrame({"subject": ["s04", "s04"], "time": [0, 12], "weight": [79.0, 77.5]})
study.add("weight", late, create_units=True)
study.units.ids("subject")
| subject | |
|---|---|
| 0 | s01 |
| 1 | s02 |
| 2 | s03 |
| 3 | s04 |
Writing a value where one already exists raises, so data are never replaced by accident. Correcting a
value is explicit with overwrite=True:
fix = pd.DataFrame({"subject": ["s01"], "time": [12], "weight": [80.6]})
try:
study.add("weight", fix)
except ValueError as err:
print(err)
study.add("weight", fix, overwrite=True)
study.to_df("weight").query("subject == 's01'")
1 value(s) of 'weight' are already stored at these addresses. Pass overwrite=True to replace them.
| subject | time | weight | |
|---|---|---|---|
| 0 | s01 | 0 | 82.1 |
| 8 | s01 | 12 | 80.6 |
An addition that fails changes nothing: neither values nor units. Here one row is out of the allowed
range, so the new subject s05 in the same table is not created either.
study.variables.update("weight", measurement_unit="kg", range=(20, 300))
bad = pd.DataFrame({"subject": ["s05", "s05"], "time": [0, 12], "weight": [70.0, 700.0]})
before = study.n_values("weight"), study.units.n_units("subject")
try:
study.add("weight", bad, create_units=True)
except ValueError as err:
print(err)
before, (study.n_values("weight"), study.units.n_units("subject"))
Variable 'weight': value(s) [700.0] outside range [20, 300].
((9, 4), (9, 4))
Units with parents¶
With nested levels, add_units can create missing parent units on the way, here the sites of new
subjects:
multi = syn.Study("Two sites")
multi.units.define("site > subject")
multi.add_units(
"subject",
pd.DataFrame({"site": ["lyon", "paris"], "subject": ["s01", "s01"], "group": ["control", "treated"]}),
create_parents=True,
)
multi.table("subject")
/tmp/ipykernel_2618/3105471678.py:3: InferenceNotice: Inferred definitions for subject variables: group: category @ subject. Review them with study.variables, or define them explicitly. multi.add_units(
| site | subject | group | |
|---|---|---|---|
| 0 | lyon | s01 | control |
| 1 | paris | s01 | treated |
added_at records when values of a variable were last added (first_added_at, when they were first
added). 12 · Pre-registration uses them to tell whether a question was written
before or after the data.
study.added_at("weight")
datetime.datetime(2026, 11, 27, 8, 23, 1, 512621, tzinfo=datetime.timezone.utc)
Next: 04 · Selecting and reshaping shows how to get data back out of a study and how to take part of it.