Extract numeric fields from a sequence of Pydantic models into a NumPy array.
| Parameters: |
-
models
(Iterable[BaseModel])
–
An iterable of Pydantic model instances to extract values from.
-
fields
(Sequence[str])
–
Ordered sequence of dot-separated field paths (case-sensitive) to
extract from each model. Each path is resolved via get_field_value.
|
| Returns: |
-
ndarray
–
Array containing the extracted values. Shape (N, F):
- N: The number of models in the input iterable.
- F: The number of requested fields.
|
Examples:
>>> class Point(BaseModel):
... x: float
... y: float
>>> points = [Point(x=1.0, y=2.0), Point(x=3.0, y=4.0)]
>>> models_to_numpy(points, ["x", "y"])
array([[1., 2.],
[3., 4.]], dtype=float32)
Source code in aidevelopementtoolkit/data_utils/pydantic_utils.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48 | def models_to_numpy(models: Iterable[BaseModel], fields: Sequence[str]) -> np.ndarray:
"""Extract numeric fields from a sequence of Pydantic models into a NumPy array.
Parameters
----------
models : Iterable[BaseModel]
An iterable of Pydantic model instances to extract values from.
fields : Sequence[str]
Ordered sequence of dot-separated field paths (case-sensitive) to
extract from each model. Each path is resolved via `get_field_value`.
Returns
-------
np.ndarray
Array containing the extracted values. Shape `(N, F)`:
- `N`: The number of models in the input iterable.
- `F`: The number of requested fields.
Examples
--------
>>> class Point(BaseModel):
... x: float
... y: float
>>> points = [Point(x=1.0, y=2.0), Point(x=3.0, y=4.0)]
>>> models_to_numpy(points, ["x", "y"])
array([[1., 2.],
[3., 4.]], dtype=float32)
"""
if not fields:
logger.error("Expected at least one field name.")
raise ValueError()
rows = [
[get_field_value(model, field) for field in fields]
for model in models
]
return np.array(rows, dtype=np.float32)
|