For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).
to_numpy_array
def to_numpy_array[dtype: DType, origin: Origin[mut=origin.mut]](data: Span[Scalar[dtype], origin]) -> PythonObject
Builds a 1-D NumPy array from a Mojo Span of scalars.
The data is copied into a new, independent NumPy array, so the result
remains valid after data is later mutated or freed.
Example:
from std.python.numpy import to_numpy_array
from std.math import sin
var values = List[Float64](capacity=1024)
for i in range(1024):
var x = Float64(i) * 0.01
values.append(sin(x) * sin(x))
var arr = to_numpy_array(values) # an independent NumPy float64 array
Constraints:
dtype must be one of the fixed-width numeric dtypes supported by
NumPy: int8-int64, uint8-uint64, float16, float32, or
float64.
Parameters:
- dtype (
DType): The element dtype of the span (inferred). - origin (
Origin[mut=origin.mut]): The origin of the span (inferred).
Args:
- data (
Span[Scalar[dtype], origin]): The scalars to copy into a NumPy array.
Returns:
PythonObject: A 1-D NumPy ndarray of dtype dtype and length len(data).
Raises:
If NumPy is unavailable, or if the underlying NumPy calls fail.