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).
from_numpy_tensor
def from_numpy_tensor[mut: Bool, //, dtype: DType, rank: Int, origin: Origin[mut=mut]](ref[origin] array: PythonObject) -> NumPyView[dtype, rank, origin]
Borrows an N-D C-contiguous NumPy array as a NumPyView.
This is the N-D counterpart of from_numpy_array: the view aliases the
array's whole buffer in C order (last axis varying fastest) and carries the
extents needed to index it. No bytes are copied, and the same aliasing
rules as from_numpy_array apply.
Example:
from std.python import Python
from std.python.numpy import from_numpy_tensor
var np = Python.import_module("numpy")
var array = np.arange(6, dtype="float64").reshape(2, 3)
var view = from_numpy_tensor[DType.float64, 2](array)
var value = view[1, 2] # array[1, 2]
var flat = view.data # the buffer as a `Span`, in C order
Constraints:
dtype must be one of the fixed-width numeric dtypes supported by
NumPy. rank must be positive.
Parameters:
- mut (
Bool): The mutability of the borrow, inferred fromarray. - dtype (
DType): The expected element dtype of the array. - rank (
Int): The expected number of dimensions. - origin (
Origin[mut=mut]): The origin of the borrow, inferred fromarray.
Args:
- array (
PythonObject): A C-contiguous NumPyndarrayofrankdimensions whose dtype matchesdtype.
Returns:
NumPyView[dtype, rank, origin]: A NumPyView of the array's buffer and shape, with the same
mutability and origin as the array binding.
Raises:
If array.ndim is not rank, is not C-contiguous, has a dtype that
does not match dtype, or is not writable when borrowed mutably.