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).
copy_to_numpy_array
def copy_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. Unlike
from_numpy_array, which returns a zero-copy view, this function does not
alias data: mutating data after this call is not reflected in the
returned array, and writes to the array are not reflected in data.
Example:
from std.python.numpy import copy_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 = copy_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.