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_tensor
def copy_to_numpy_tensor[dtype: DType, origin: ImmOrigin, *shape_types: CoordLike](data: Span[Scalar[dtype], origin], shape: Coord[shape_types]) -> PythonObject
Builds an N-D NumPy array from a Mojo Span of scalars and a shape.
The span supplies the elements in C order (last axis varying fastest) and
shape supplies the extents, so shape.product() must equal len(data).
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 copy_to_numpy_tensor
from std.utils.coord import Coord, Idx
var values = List[Float64](capacity=6)
for i in range(6):
values.append(Float64(i))
var arr = copy_to_numpy_tensor(values, Coord(Idx[2], Idx[3])) # 2x3 array
Dimensions may be compile-time (Idx[N]) or runtime (Int) in any mix.
Constraints:
dtype must be one of the fixed-width numeric dtypes supported by
NumPy: int8-int64, uint8-uint64, float16, float32, or
float64. shape must be flat (no nested Coord) and must not
contain All.
Parameters:
- dtype (
DType): The element dtype of the span (inferred). - origin (
ImmOrigin): The origin of the span (inferred). - *shape_types (
CoordLike): The per-dimension types ofshape(inferred).
Args:
- data (
Span[Scalar[dtype], origin]): The scalars to copy into a NumPy array, in C order. - shape (
Coord[shape_types]): The extents of the result, one element per axis.
Returns:
PythonObject: A NumPy ndarray of dtype dtype and shape shape.
Raises:
If shape.product() does not equal len(data), if NumPy is
unavailable, or if the underlying NumPy calls fail.