Table of Contents

Class NDArray

Namespace
NumSharp
Assembly
NumSharp.dll

Container protocol implementation for NDArray. Provides Python-compatible container protocol methods: contains, hash, len, iter, getitem, setitem

[SuppressMessage("ReSharper", "ParameterHidesMember")]
[ModuleName("ndarray")]
[SuppressMessage("ReSharper", "ParameterHidesMember")]
[SuppressMessage("ReSharper", "ParameterHidesMember")]
[SuppressMessage("ReSharper", "ParameterHidesMember")]
[SuppressMessage("ReSharper", "CoVariantArrayConversion")]
[SuppressMessage("ReSharper", "ParameterHidesMember")]
[SuppressMessage("ReSharper", "ParameterHidesMember")]
public class NDArray : IIndex, ICloneable, IEnumerable, IDisposable
Inheritance
NDArray
Implements
Derived
NDArray<TDType>
Inherited Members
Extension Methods

Remarks

Constructors

NDArray(IArraySlice, Shape, char)

Wraps an existing IArraySlice as an NDArray — the C# port of NumPy's np.ndarray(shape, buffer=values, order=order) for NumSharp's own buffers. The slice's element type is the dtype, and shape contributes its DIMENSIONS only: the array lays the slice out densely in order, whatever strides or offset the shape carried.

public NDArray(IArraySlice values, Shape shape = default, char order = 'C')

Parameters

values IArraySlice

The buffer, wrapped without a copy: the result reads and writes these elements, and shares the slice's memory lifetime.

shape Shape

The dimensions of the result, like NumPy's shape argument. Only Dimensions is read (see NDArray(Array, Shape, char)). default makes a one-dimensional array of values.Count elements.

order char

'C' (the default) lays the slice out row-major and 'F' column-major, for every number of dimensions. 'A' and 'K' mean 'C', as in NumPy's ndarray; lowercase is accepted.

Remarks

This constructor is public API, so it follows NumPy's dimensions-only rule (ForWrappedBuffer(char)). To install a specific layout over a fresh buffer, internal code uses new UnmanagedStorage(slice, shape), which trusts its layout.

Exceptions

NullReferenceException

values is null (its type code is read first).

ValueError

order is not one of 'C', 'F', 'A', 'K' in either case.

TypeError

values holds fewer elements than shape needs (NumPy's buffer is too small for requested array). A larger slice is fine: the result views its first elements.

ValueError

A dimension is negative (other than the lone -1), or the byte count overflows.

NDArray(UnmanagedStorage)

Creates a new NDArray with this storage.

public NDArray(UnmanagedStorage storage)

Parameters

storage UnmanagedStorage

The storage, used as it is (not copied, not aliased): the array reads and writes it.

Remarks

The array binds the storage's engine (Engine, which a view's storage takes from its source), or Default when the storage has none (a storage built directly over a buffer), and writes it back into the storage.

NDArray(UnmanagedStorage, Shape)

Creates a new NDArray with this storage.

protected NDArray(UnmanagedStorage storage, Shape shape)

Parameters

storage UnmanagedStorage

The storage whose buffer the array views (through an alias, so the storage keeps its own shape).

shape Shape

The shape to set for this NDArray, does not perform checks.

Remarks

Doesn't copy. Does not perform checks for shape. Binds the storage's engine, or Default when it has none.

NDArray(UnmanagedStorage, ref Shape)

Creates a new NDArray with this storage.

protected NDArray(UnmanagedStorage storage, ref Shape shape)

Parameters

storage UnmanagedStorage

The storage whose buffer the array views (through an alias, so the storage keeps its own shape).

shape Shape

The shape to set for this NDArray, does not perform checks.

Remarks

Doesn't copy. Does not perform checks for shape. Binds the storage's engine, or Default when it has none.

NDArray(DType)

Constructor for init data type internal storage is 1D with 1 element

public NDArray(DType dtype)

Parameters

dtype DType

The dtype DESCRIPTOR of the elements. A C# Type (typeof(double)), an NPTypeCode or a NumPy dtype string ("f8") convert implicitly — this is the ONE dtype-taking constructor family (the former NPTypeCode twins were folded into it).

Remarks

This constructor does not call allocation. The array binds Default as it is now: an engine assigned there later does not reach it.

NDArray(DType, Shape)

Constructor which initialize elements with 0 type and shape are given.

public NDArray(DType dtype, Shape shape)

Parameters

dtype DType

The dtype descriptor (a Type, NPTypeCode or NumPy dtype string converts implicitly)

shape Shape

Shape of NDArray

Remarks

This constructor calls Allocate(Shape, DType, bool)

NDArray(DType, Shape, bool)

Constructor which initialize elements with 0 type and shape are given.

public NDArray(DType dtype, Shape shape, bool fillZeros)

Parameters

dtype DType

The dtype descriptor (a Type, NPTypeCode or NumPy dtype string converts implicitly)

shape Shape

Shape of NDArray

fillZeros bool

Should set the values of the new allocation to default(dtype)? otherwise - old memory noise

Remarks

This constructor calls Allocate(Shape, DType, bool)

NDArray(DType, Shape, bool, TensorEngine)

The allocation constructor behind NewArray(DType, Shape, bool): a new array bound to engine instead of Default, its storage from that engine's GetStorage(DType).

public NDArray(DType dtype, Shape shape, bool fillZeros, TensorEngine engine)

Parameters

dtype DType

The dtype descriptor.

shape Shape

The dimensions (a view's layout is laid out again in C order, as for every allocation).

fillZeros bool

Zero the buffer; false leaves pool noise the caller must overwrite completely.

engine TensorEngine

The engine the array binds (the engine computing the result it will hold), or null for Default as it is now.

Remarks

The constructor a custom engine or an array subclass allocates through when the result must compute on a given engine. Footgun: fillZeros false hands out whatever bytes the buffer pool held - the caller must overwrite every element before anything reads the array.

Exceptions

ValueError

A dimension is negative, or the byte count overflows.

NDArray(DType, Shape, char)

Constructor which initialize elements with 0 type, shape, and order are given.

public NDArray(DType dtype, Shape shape, char order)

Parameters

dtype DType

internal data type

shape Shape

Shape of NDArray

order char

Memory order. Note: Only C-order is supported, F-order parameter is accepted but ignored.

Remarks

This constructor calls Allocate(Shape, DType, bool)

NDArray(DType, TensorEngine)

Constructor for init data type internal storage is 1D with 1 element

protected NDArray(DType dtype, TensorEngine engine)

Parameters

dtype DType

The dtype DESCRIPTOR of the elements (NumPy's PyArray_NewFromDescr). A C# Type, an NPTypeCode or a NumPy dtype string convert implicitly.

engine TensorEngine

The engine of this NDArray

Remarks

This constructor does not call allocation/>

NDArray(DType, int)

Constructor which initialize elements with length of size

public NDArray(DType dtype, int size)

Parameters

dtype DType

Internal data type

size int

The size as a single dimension shape

Remarks

This constructor calls Allocate(Shape, DType, bool)

NDArray(DType, int, bool)

Constructor which initialize elements with length of size

public NDArray(DType dtype, int size, bool fillZeros)

Parameters

dtype DType

Internal data type

size int

The size as a single dimension shape

fillZeros bool

Should set the values of the new allocation to default(dtype)? otherwise - old memory noise

Remarks

This constructor calls Allocate(Shape, DType, bool)

NDArray(DType, long)

Constructor which initialize elements with length of size (long for >2GB arrays)

public NDArray(DType dtype, long size)

Parameters

dtype DType

Internal data type

size long

The size as a single dimension shape

Remarks

This constructor calls Allocate(Shape, DType, bool)

NDArray(DType, long, bool)

Constructor which initialize elements with length of size (long for >2GB arrays)

public NDArray(DType dtype, long size, bool fillZeros)

Parameters

dtype DType

Internal data type

size long

The size as a single dimension shape

fillZeros bool

Should set the values of the new allocation to default(dtype)? otherwise - old memory noise

Remarks

This constructor calls Allocate(Shape, DType, bool)

NDArray(Array, Shape, char)

Wraps a .NET array as an NDArray — the C# port of NumPy's np.ndarray(shape, buffer=values, order=order). The element type of values is the dtype, and shape contributes its DIMENSIONS only: the array lays values out densely in order, whatever strides or offset the shape carried.

public NDArray(Array values, Shape shape = default, char order = 'C')

Parameters

values Array

The elements, read in the order order lays them out. A one-dimensional array is wrapped in place, without a copy, so writes through the result reach it. A multi-dimensional or jagged array is first flattened, row by row, into a new one-dimensional array.

shape Shape

The dimensions of the result, like NumPy's shape argument. Only Dimensions is read: the shape of a view (x.Shape of a[::4], a[::-1], a.T or a broadcast) gives the same array as a fresh shape of the same dimensions. default (an uninitialized Shape) uses the dimensions of values itself.

order char

'C' (the default) lays the values out row-major and 'F' column-major, for every number of dimensions. 'A' and 'K' mean 'C' here, as in NumPy's ndarray; lowercase is accepted.

Remarks

Why dimensions only. NumPy's array_new computes the strides for shape itself (_array_fill_strides), so the port new NDArray(values, x.Shape) of np.ndarray(x.shape, buffer=values) must not install a view's layout over the caller's buffer. It used to: for x = arange(20)["::4"] element i was read at i * 4 of a 5-element array, past its end; a reversed view's shape read the values backwards, a transposed view's in F order, and a broadcast view's repeated row 0 and made the result read-only. ForWrappedBuffer(char) is the rule.

Internal code that must install a specific layout over a fresh buffer (a KEEPORDER result) builds the storage with new UnmanagedStorage(slice, shape) instead, which trusts its layout as NumPy's C API does.

Exceptions

NullReferenceException

values is null (its element type is read first).

ValueError

order is not one of 'C', 'F', 'A', 'K' in either case (NumPy's text: order must be one of 'C', 'F', 'A', or 'K' (got 'X')).

TypeError

values holds fewer elements than shape needs (NumPy's buffer is too small for requested array). A larger array is fine: the result views its first elements, as NumPy reads a prefix of a larger buffer.

ValueError

A dimension is negative (other than the lone -1, which takes every element), or the byte count overflows.

Fields

Storage

The internal storage that stores data for this NDArray.

protected UnmanagedStorage Storage

Field Value

UnmanagedStorage

tensorEngine

protected TensorEngine tensorEngine

Field Value

TensorEngine

Properties

Address

Gets the address that this NDArray starts from.

protected void* Address { get; }

Property Value

void*

Array

The storage's internal array (InternalArray): the slice that holds this array's elements, read through Shape (a view shares its owner's slice).

protected IArraySlice Array { get; }

Property Value

IArraySlice

IsDisposed

true if Dispose() has been called on this NDArray. Views and shared storage may still be alive; this flag only reflects the local instance.

public bool IsDisposed { get; }

Property Value

bool

this[object[]]

NumPy's ndarray.getitem(key) and ndarray.setitem(key, value): the one indexer of an array. The C# argument list is NumPy's index tuple (a[1, 2] is NumPy's a[(1, 2)]), and an entry is any index NumPy takes: an integer, a Slice, slice notation (a[":, 2:7:1, ..., np.newaxis"]), Ellipsis and NewAxis, an integer index array (an NDArray, int[], long[] or any integer sequence), a boolean mask (an NDArray of bool, bool[], bool[,] or any bool sequence) and a C# bool (NumPy's 0-d bool).

public virtual NDArray this[params object[] key] { get; set; }

Parameters

key object[]

The index tuple. One entry per C# argument; a Slice[] or object[] passed alone is the tuple itself, and a single C# tuple entry (a[(1, "0:2")]) is spread into its entries, as Python reads a[(1, 2)] as a[1, 2]. A lone string holds the whole index in slice notation (comma-separated); a string among other entries is one slice.

Property Value

NDArray

GET: for one integer per axis (and () of a 0-d array) NumPy's SCALAR, the element as NumPy's array_item returns it: a new read-only 0-d array holding a COPY of the element, which does not change when this array does (write an element through the setter, a[i] = v); a VIEW for any other index of integers, slices, the ellipsis and new axes (a 0-d view, a[0, ...] or z[...], is an explicit 0-d array that writes through); for a NumPy scalar itself, a non-item index (s[...], s[None]) views a writeable copy of its value (NumPy's gentype_subscript); a new array for an index array, a mask or a C# bool (NumPy's advanced indexing). SET: stores the value into the selection by NumPy's rules: a value broadcasts to the selection, a C# number is NumPy's Python scalar (range-checked, never wrapped), one integer per axis stores one element (a StringDType element takes a Python object by setitem).

Remarks

Dispatch. The key is sorted before any work, so each kind runs the code of the typed indexer that served it until this one replaced them (this[string], this[params Slice[]], this[NDArray<bool>], this[params NDArray<int>[]], this[long*, int]), and a call keeps its result and its error: a basic index (see TryBasicIndex(object[], out Slice[])) is one view of the storage; a lone NDArray<TDType> of bool is the mask path; every other key is the general advanced path. The pre-dispatch matters beyond speed: the general path has no case for a lone long or short, which C# used to bind to the Slice indexer at compile time.

Virtual. NDArray<TDType> overrides the GETTER to type its result (typed["1:3"] is an NDArray<TDType>) and inherits this setter. NDCharArray and NDMatrix declare their own indexer instead of overriding: their rules (a stripped element, a matrix row or column) apply through their static type, and through an NDArray reference they are indexed as plain arrays, which the library's own code relies on (it receives such objects as NDArray, see NumSharp.PlainReceiverAttribute).

https://numpy.org/doc/stable/user/basics.indexing.html

Exceptions

ArgumentNullException

key is null, or an entry is null (NumPy's None is NewAxis).

IndexError

An integer is out of bounds, there are more indices than axes, a mask does not match the axes it indexes, index arrays do not broadcast together, or an entry is not a valid index (NumPy's prepare_index texts).

ValueError

SET: the array is read-only (checked first, as NumPy's setitem does), the value does not broadcast to the selection, or a sequence is stored into one element.

OverflowError

SET: a C# integer outside this array's integer dtype (NumPy's OverflowError).

TypeError

SET: a complex number into a real array, or a value of two or more dimensions through a mask of this array's own shape.

ReprClassName

The class name NumPy's repr() prints before the opening parenthesis: array for an ndarray, the subclass name for a subclass (type(arr).name in _array_repr_implementation). Override it in a subclass that NumPy prints under another name; the continuation lines and a wrapped dtype= suffix are aligned to this name's length, so it changes the layout of the whole repr, not the first word alone.

protected virtual string ReprClassName { get; }

Property Value

string

The name without the parenthesis. Never null or empty.

Remarks

A subclass declared outside NumSharp.dll overrides it as protected override; NumPy prints a user subclass under its own name, which is what such an override should return.

Shape

The shape representing this NDArray. Assigning it reshapes the array IN PLACE to the given shape's dimensions (its strides/offset are ignored) under NumPy's ndarray.shape setter rule — see SetShapeInPlace(Shape).

public Shape Shape { get; set; }

Property Value

Shape

Exceptions

AttributeError

(set) The new dimensions need a copy; NumPy's message verbatim.

IncorrectShapeException

(set) The new shape's size differs from the array's.

T

The transposed array.
Same as self.transpose().

public NDArray T { get; }

Property Value

NDArray

Remarks

TensorEngine

The engine this array computes on: np.* functions given this array as their operand call this engine's members, and the arrays they return bind it too (an engine binds its results to itself, a view its source's engine).

public TensorEngine TensorEngine { get; set; }

Property Value

TensorEngine

The engine the array bound when it was created (Default unless an engine created it or it views another array), or the engine assigned since; never null. An array that bound no engine resolves to Default as it is at the read.

Remarks

Assigning moves this array, and the storage object it holds, to another engine; assigning null binds Default as it is now. Arrays that view the same buffer through storages of their own (other views, the base array) keep their engines.

Unsafe

Provides an interface for unsafe methods in NDArray.

public NDArray._Unsafe Unsafe { get; }

Property Value

NDArray._Unsafe

__array_priority__

NumPy's ndarray.array_priority: 0.0 for an ndarray (and a chararray, which declares none). The class wrap of a ufunc result (npy_find_array_wrap) and the subtype of a sequence function (PyArray_GetSubType) go to the subclass operand of the highest priority, so a matrix (10.0) wins over both.

public virtual double __array_priority__ { get; }

Property Value

double

Remarks

Read only for a subclass operand: a plain array never takes part in the choice.

base

Gets the array owning the memory, or null if this array owns its data.

public NDArray? @base { get; }

Property Value

NDArray

An NDArray wrapping the base storage for views, or null for arrays that own their data (e.g., created via np.arange, np.zeros, or copy()).

Remarks

NumPy Compatibility: This property mirrors NumPy's ndarray.base attribute. All views chain to the ultimate owner (not intermediate views).

Example:

var a = np.arange(10);    // a.@base == null (owns data)
var b = a["2:5"];         // b.@base.Storage == a.Storage (view)
var c = b["1:2"];         // c.@base.Storage == a.Storage (chains to original!)
var d = a.copy();         // d.@base == null (copy owns data)
var e = a.reshape(2, 5);  // e.@base.Storage == a.Storage (view)

View Detection: Use arr.@base != null or arr.Storage.IsView to detect if an array is a view. Note that arr.@base != null may trigger NDArray's operator overloading for element-wise comparison. Prefer arr.Storage.IsView for simple boolean checks.

Semantic Difference from NumPy: In NumPy, c.base is a returns True (object identity). In NumSharp, c.@base creates a new wrapper each call, so ReferenceEquals(c.@base, a) is false. However, the underlying storage is the same: c.@base.Storage == a.Storage is true.

Memory Safety: The underlying memory is kept alive by the shared Disposer in the MemoryBlock, not by this property. Views remain valid even if the original array reference is garbage collected.

See Also

data

Python buffer object pointing to the start of the array's data — the NumSharp analog of NumPy's ndarray.data (which is literally memoryview(self)). Returns a zero-copy np.MemoryView handle over this array's memory: it exposes the raw Pointer at the LOGICAL first element (so a sliced or reversed view reports its offset element, matching NumPy's a.data / a.ctypes.data), the buffer metadata (nbytes / itemsize / ndim / shape / strides in bytes / format / readonly / contiguity), write-through element access, and tobytes. Read-only, like NumPy's attribute (which raises AttributeError on assignment); a fresh handle is returned per access. See Data<T>() / GetData() for the typed / raw-slice accessors.

public np.MemoryView data { get; }

Property Value

np.MemoryView

Remarks

Exceptions

ValueError

A NEP 55 StringDType array (NumPy's buffer export refuses reference dtypes).

device

The device on which this array lives. NumSharp — like NumPy — is single-device and always CPU-resident, so this is always the string "cpu". Exposed for Array-API conformance, so code such as xp.zeros(shape, device: x.device) ports from NumPy unchanged.

public string device { get; }

Property Value

string

Remarks

dtype

The dtype of this array — the dtype DESCRIPTOR (NumPy's ndarray.dtype, a DType): the canonical instance of the array's dtype class (np.float64 for a double array — the same object every time, so a.dtype == b.dtype and a.dtype == np.float64 are cheap structural compares), or the parametric instance an array was created with. It converts implicitly to the CLR element Type (Type t = a.dtype;) and to NPTypeCode, and compares equal to a Type / NPTypeCode / dtype string the way NumPy's dtype.eq coerces (a.dtype == typeof(double), a.dtype.Equals("f8")). Use typecode for the kernel discriminator and dtype.type for the element type when a Type is required by name.

public DType dtype { get; }

Property Value

DType

dtypesize

The in-memory element size in bytes that NumSharp's raw element routes copy with (the legacy alias of itemsize for every numeric and fixed-width string dtype).

public int dtypesize { get; }

Property Value

int

Exceptions

NotSupportedException

The array holds NEP 55 StringDType text: its elements are 16-byte cells that only their own buffer's allocator can read, so no element can be copied as raw bytes and this property refuses (read itemsize for NumPy's 16).

flags

Information about the memory layout of the array — the NumSharp analog of NumPy's ndarray.flags (an arrayflags object). A fresh NDArrayFlags is returned per access; it reads LIVE from this array (and its writeable setter mutates this array), so a.flags.c_contiguous, a.flags["F"] and Console.Write(a.flags) all port from NumPy unchanged.

public NDArrayFlags flags { get; }

Property Value

NDArrayFlags

Remarks

flat

A 1-D iterator over the array.

public NDArray flat { get; }

Property Value

NDArray

Remarks

flatiter

A write-through, C-order flat iterator over the array — the NumSharp analog of NumPy's flatiter (the type of NumPy's ndarray.flat). Unlike flat (a raveled NDArray that COPIES for a non-contiguous layout, dropping writes), this reads and writes through to the base in logical C-order for every memory layout. A fresh iterator is returned on each access (its cursor starts at 0).

public np.FlatIterator flatiter { get; }

Property Value

np.FlatIterator

Remarks

imag

The imaginary part of the array (NumPy's ndarray.imag) — a read/write accessor.

GET: for a COMPLEX array, a float64 VIEW onto the imaginary lane that SHARES memory and is writeable; for a real / integer / boolean array, a fresh READ-ONLY all-zeros array of the same shape and dtype (the imaginary part of a real number is zero). Delegates to imag(NDArray).

SET: for a COMPLEX array, copies value into the imaginary lane (same UNSAFE-cast, broadcasting PyArray_CopyInto semantics as real). For a real array there is no imaginary lane to write, so it raises TypeError ("array does not have imaginary part to set"), matching NumPy.

public NDArray imag { get; set; }

Property Value

NDArray

Remarks

Exceptions

TypeError

Assigned to a non-complex array (NumPy raises the same message).

itemsize

Length of one array element in bytes — NumPy's ndarray.itemsize. This is a pure property of the dtype and is independent of shape, strides, offset or layout, so every view of a given dtype (C/F-contiguous, sliced, strided, transposed, negative-stride, broadcast, 0-d or empty) reports the same value. Byte-identical to NumPy for the 13 dtypes with a NumPy analog (e.g. float64→8, complex128→16, int8/bool→1); the two NumSharp-only dtypes report their in-memory element size (Char→2, Decimal→16). Alias of the legacy dtypesize; the product size * itemsize is nbytes.

public int itemsize { get; }

Property Value

int

Remarks

mT

View of the matrix transposed array.
Swaps the two innermost dimensions, i.e. an array of shape (..., M, N) becomes (..., N, M).
Same as np.matrix_transpose(self) / self.swapaxes(-1, -2). Requires at least 2 dimensions.

public NDArray mT { get; }

Property Value

NDArray

Remarks

Exceptions

ArgumentException

If this array has fewer than 2 dimensions.

nbytes

Total bytes consumed by the elements of the array — the LOGICAL element count (size) times the itemsize (dtypesize), matching NumPy's PyArray_NBYTES = PyArray_ITEMSIZE * PyArray_SIZE. Because it uses the logical size, a broadcast view reports its logical byte size (e.g. a (1000,1000) stride-0 view of one int32 reports 4000000), not its one-element backing buffer; a 0-d array reports one itemsize and an empty array reports 0. Does not include the array object's own overhead.

public long nbytes { get; }

Property Value

long

Remarks

ndim

Dimension count

public int ndim { get; }

Property Value

int

order

public char order { get; }

Property Value

char

real

The real part of the array (NumPy's ndarray.real) — a read/write accessor.

GET: for a COMPLEX array, a float64 VIEW onto the real lane that SHARES memory and is writeable (so z.real[i] = x writes through to z[i]'s real part); for a real / integer / boolean array, the array itself (the real part of a real number is the number), dtype preserved. Delegates to real(NDArray).

SET: copies value into the real part (broadcasting to its shape) with NumPy's PyArray_CopyInto semantics — UNSAFE casting, so a float value assigned to an integer array TRUNCATES (a.real = 3.9 stores 3), an out-of-range integer WRAPS (int8.real = 300 stores 44), and a complex value keeps only its real part. For a real array this overwrites the whole array (a.real = 5); for a complex array it overwrites only the real lane, leaving the imaginary parts untouched. Writing to a read-only array raises the standard read-only error.

public NDArray real { get; set; }

Property Value

NDArray

Remarks

shape

Data length of every dimension (NumPy's ndarray.shape), as a NEW array on every read: NumPy hands out an immutable tuple, so writing into the returned array never changes this array. Assigning the property reshapes the array IN PLACE — only when the new shape is expressible over the existing memory; see SetShapeInPlace(Shape) for the exact rule and the error it raises otherwise.

public long[] shape { get; set; }

Property Value

long[]

(get) A copy of the dimensions, the caller's to keep or change; a 0-d array returns an empty array. (set) The new dimensions, read once (a later change to the caller's array does not reach this array).

Remarks

Why a copy. Shapes and arrays SHARE dimension arrays (an allocation keeps its caller's shape, an elementwise result keeps its input's), so returning the shared array let var d = a.shape; d[0] = 100; change a — and every array sharing it — to (100, 4) over 12 elements: the cached size and the buffer stayed, so the new rows read past the buffer. Plan docs/plans/view-shape-open-bugs.md, bug 2b.

The copy costs one small allocation per read. Code inside NumSharp reads Shape.dimensions instead; user code that reads shape in a hot loop should hoist it.

Exceptions

AttributeError

(set) The new shape needs a copy (e.g. flattening a transposed view); NumPy's message verbatim — use reshape(params long[]) to get a copy.

IncorrectShapeException

(set) The new shape's size differs from the array's.

size

Total of elements

public long size { get; }

Property Value

long

strides

The strides of the array, in BYTES per axis — matching NumPy's ndarray.strides (PyArray_STRIDES): the number of bytes to step in memory to advance one element along each dimension. Equal to the element strides times the dtypesize (itemsize), so a stride-0 broadcast axis stays 0 and a negative-stride (reversed) view stays negative. A 0-d array reports an empty array. A fresh array is returned on each access. ELEMENT strides are Strides (also a fresh array per read); code inside NumSharp reads the internal Shape.strides field, which does not allocate.

public long[] strides { get; }

Property Value

long[]

Remarks

typecode

The NPTypeCode of this array.

public NPTypeCode typecode { get; }

Property Value

NPTypeCode

Methods

AsGeneric<T>()

Tries to cast to NDArray<TDType>; if that fails but the dtype already matches, wraps the existing storage. Returns null when T != dtype (try-cast / as semantics — never throws).

public NDArray<T> AsGeneric<T>() where T : unmanaged

Returns

NDArray<T>

This NDArray as a generic version, or null when T != dtype.

Type Parameters

T

The type of the generic

Remarks

The zero-data-alloc fast path returns this when it is already an NDArray<TDType>. Otherwise it wraps the same storage; this is intended for freshly-produced engine results (e.g. comparison outputs), so the wrapped storage is not aliased.

AsOrMakeGeneric<T>()

When the dtype already matches, returns an independent typed view (alias) sharing this array's data; otherwise converts the storage to T via the NDIter-backed Cast<T>() (a fresh, owned copy). Never throws on dtype mismatch.

public NDArray<T> AsOrMakeGeneric<T>() where T : unmanaged

Returns

NDArray<T>

This NDArray as a generic version, sharing data when the dtype matches.

Type Parameters

T

The type of the generic

Remarks

The matching branch aliases (see MakeGeneric<T>()) so a later reshape of the result does not mutate this array's shape; the converting branch already owns fresh storage.

AsString(NDArray)

Converts the entire NDArray to a string.

public static string AsString(NDArray arr)

Parameters

arr NDArray

Returns

string

Remarks

Performs a copy due to String .net-framework limitations. NDAnchoredAttribute (lost-anchor site LT29): the string is allocated before the chars are copied out of the buffer, so arr is rooted to the end — a temporary argument could otherwise be collected, and its buffer freed, by a collection that the allocation triggers.

AsStringArray(NDArray)

The elements of a fixed-width Unicode (U) array as C# strings, in C order — NumPy's arr.ravel().tolist(). Each value has its trailing NULs removed (NumPy's getitem); any layout (strided, transposed, broadcast) is read in logical order.

public static string[] AsStringArray(NDArray arr)

Parameters

arr NDArray

A U array of any shape.

Returns

string[]

The values.

Remarks

Breaking: this used to parse the "N l1 l2:contents" char-vector layout the old np.array(string[]) produced; that layout no longer exists.

A NEP 55 StringDType array is accepted too: each element is its text, an NA element the descriptor's NA object when that is a string or None (null); an NA element of any other NA object (a float NaN) cannot be a C# string and is refused — read such arrays with tolist().

NDAnchoredAttribute (lost-anchor site LT29): the contiguous path reads the buffer through a raw pointer while it allocates one string per element, so arr is rooted to the end. Without it a temporary argument (NDArray.AsStringArray(np.char.upper(a))) was reachable from nothing during the loop: a collection finalized its memory block and the loop read freed memory (an access violation for a 200 MB U500 array, reproduced).

Exceptions

ArgumentNullException

arr is null.

InvalidCastException

arr is not a U array (an S array's elements are bytes: read them with ToArray<byte[]>-style element access).

SystemError

A unit above U+10FFFF.

Clone()

Clone the whole NDArray internal storage is also cloned into 2nd memory area

public virtual NDArray Clone()

Returns

NDArray

Cloned NDArray

CloneData()

public IArraySlice CloneData()

Returns

IArraySlice

CloneData<T>()

public ArraySlice<T> CloneData<T>() where T : unmanaged

Returns

ArraySlice<T>

Type Parameters

T

Contains(object)

Returns true if value is found in the array (linear search). Equivalent to NumPy's value in arr.

public bool Contains(object value)

Parameters

value object

Value to search for.

Returns

bool

True if value exists in the array.

Examples

var arr = np.array(new[] { 1, 2, 3, 4, 5 });
arr.Contains(3);  // true
arr.Contains(10); // false

Remarks

This is a linear O(n) search. For sorted arrays, consider using np.searchsorted. NaN handling: NaN == NaN is false in IEEE 754, so Contains(float.NaN) returns false for arrays containing NaN. Use np.any(np.isnan(arr)) to check for NaN.

CopyTo(IMemoryBlock)

Copies the entire contents of this storage to given address (size elements).

public void CopyTo(IMemoryBlock slice)

Parameters

slice IMemoryBlock

The slice to copy to.

CopyTo(nint)

Copies the entire contents of this storage to given address.

public void CopyTo(nint ptr)

Parameters

ptr nint

CopyTo(void*)

Copies the entire contents of this storage to given address (size elements).

public void CopyTo(void* address)

Parameters

address void*

The address to copy to.

CopyTo<T>(IMemoryBlock<T>)

Copies the entire contents of this storage to given address (size elements).

public void CopyTo<T>(IMemoryBlock<T> block) where T : unmanaged

Parameters

block IMemoryBlock<T>

The slice to copy to.

Type Parameters

T

CopyTo<T>(T*)

Copies the entire contents of this storage to given address.

public void CopyTo<T>(T* address) where T : unmanaged

Parameters

address T*

The address to copy to.

Type Parameters

T

CopyTo<T>(T[])

Copies the entire contents of this storage to given array.

public void CopyTo<T>(T[] array) where T : unmanaged

Parameters

array T[]

The array to copy to.

Type Parameters

T

Data<T>()

Shortcut for access internal elements

public ArraySlice<T> Data<T>() where T : unmanaged

Returns

ArraySlice<T>

Type Parameters

T

Dispose()

Releases this NDArray's reference to the underlying unmanaged buffer. When the last reference is released the buffer is freed synchronously on the calling thread; views that still hold references keep working.

Safe to call multiple times — second and subsequent calls are no-ops.

public void Dispose()

Equals(object)

Determines if NDArray data is same

public override bool Equals(object obj)

Parameters

obj object

NDArray to compare

Returns

bool

if reference is same

ExpandEllipsis(object[], int)

protected static IEnumerable<object> ExpandEllipsis(object[] ndarrays, int ndim)

Parameters

ndarrays object[]
ndim int

Returns

IEnumerable<object>

FetchIndices(NDArray, NDArray[], NDArray, bool)

The typed fetch an advanced index ends in (NumPy's mapiter_get, with mapiter_trivial_get's route for one index array): the elements of src at the positions the integer index arrays name — one array per leading axis, broadcast together — gathered into a new array of shape broadcast(index shapes) + src.shape[len(indices):], or into out. Picks the element type from src's storage lane and runs MapIterGet<T>(NDArray<T>, NDArray[], NDArray, bool).

protected static NDArray FetchIndices(NDArray src, NDArray[] indices, NDArray @out, bool extraDim)

Parameters

src NDArray

The array read, any layout (a 0-d one is read as (1,), a broadcast one copied first).

indices NDArray[]

One integer index array per leading axis (any integer dtype; a mask arrives as its nonzero). The array is REWRITTEN: its entries are replaced by their normalized forms (int32 / int64, broadcast, flattened). The indexers bounds-check the values first (PrepareIndex); a value out of range still raises here.

out NDArray

A destination of the result's shape and element type, or null for a new array.

extraDim bool

Not read; carried for the signature of NDArray.FetchIndices, which forwards here.

Returns

NDArray

The gathered array: a new C-contiguous array that owns its data (NumPy's fancy result), or out (as a typed view when it was not one).

Remarks

[NDScoped]: the per-dispatch MakeGeneric alias, the offsets buffer and every gather temporary are released when the call returns, exceptions included; the result (or the caller's out, which the scope does not track) is the only survivor.

Exceptions

ArgumentNullException

src or indices is null.

ArgumentException

indices is empty, or out has another shape or element type.

IndexError

More index arrays than src has axes, or an index value out of bounds (NumPy's texts).

IndexOutOfRangeException

The memory-safety backstop: a computed offset outside a buffer, which only a miscomputed shape reaches.

NotSupportedException

A text lane: a fixed-width or StringDType array has no typed fetch here (the indexers run its index on a unit or cell view, whose lanes are numeric).

FetchIndicesNDNonLinear<T>(NDArray<T>, NDArray[], int, long[], long[], NDArray)

The subspace copy of mapiter_get for a source that is not C-contiguous (transposed, row- or column-strided, reversed): each selected position's sub-array is walked element by element through the source's strides (an odometer over subShape, last axis fastest) into the C-ordered result, as NumPy gathers a strided source into a fresh contiguous array. One GetOffset per element, so slower than MapIterGetSubspace<T>(NDArray<T>, NDArray<long>, NDArray[], int, long[], long[], NDArray)'s block copies; use it only where those would be wrong.

protected static NDArray<T> FetchIndicesNDNonLinear<T>(NDArray<T> source, NDArray[] indices, int ndsCount, long[] retShape, long[] subShape, NDArray @out) where T : unmanaged

Parameters

source NDArray<T>

The source, any non-contiguous layout.

indices NDArray[]

One flat integer index array per consumed leading axis, broadcast together.

ndsCount int

The number of leading axes the index arrays consume.

retShape long[]

The result's shape: the broadcast index shape followed by subShape.

subShape long[]

The trailing axes each position copies.

out NDArray

A destination of retShape and T, or null.

Returns

NDArray<T>

The result (a new C-contiguous array), or a typed view of out.

Type Parameters

T

The element type.

Remarks

Forwards to MapIterGetSubspaceStrided<T>(NDArray<T>, NDArray[], int, long[], long[], NDArray) (moved there 2026-10-29); kept under its old name for types that derive from NDArray.

Exceptions

ArgumentException

out has another shape or element type.

IndexError

An index value out of bounds (from PrepareIndexGetters(Shape, NDArray[])'s getters).

IndexOutOfRangeException

An element outside the source's or the result's buffer: the memory-safety guard.

FetchIndicesND<T>(NDArray<T>, NDArray<long>, NDArray[], int, long[], long[], NDArray)

The subspace copy of mapiter_get for a C-contiguous source: each selected position's sub-array (the axes the index arrays leave, subShape) is ONE contiguous block there, copied whole from the precomputed element offset into the C-ordered result. Use only when the source is C-contiguous; a strided source's sub-arrays are not blocks (MapIterGetSubspaceStrided<T>(NDArray<T>, NDArray[], int, long[], long[], NDArray)).

protected static NDArray<T> FetchIndicesND<T>(NDArray<T> src, NDArray<long> offsets, NDArray[] indices, int ndsCount, long[] retShape, long[] subShape, NDArray @out) where T : unmanaged

Parameters

src NDArray<T>

The C-contiguous source; the offsets index its buffer, its view offset included.

offsets NDArray<long>

One element offset per selected position (1-D), from the index arrays.

indices NDArray[]

Not read (the index arrays the offsets came from).

ndsCount int

Not read (the number of leading axes the index arrays consume).

retShape long[]

The result's shape: the broadcast index shape followed by subShape.

subShape long[]

The trailing axes each position copies.

out NDArray

A destination of retShape and T, or null.

Returns

NDArray<T>

The owned result INSTANCE (never a MakeGeneric alias of it, which would misreport flags.owndata as False), or out itself (a typed view of it when it is not an NDArray<TDType>).

Type Parameters

T

The element type.

Remarks

Forwards to MapIterGetSubspace<T>(NDArray<T>, NDArray<long>, NDArray[], int, long[], long[], NDArray) (moved there 2026-10-29); kept under its old name for types that derive from NDArray.

Exceptions

ArgumentException

out has another shape or element type.

IndexOutOfRangeException

A block outside the source's or the result's buffer: the memory-safety guard (the offsets' check upstream validates each block's start only).

FetchIndices<T>(NDArray<T>, NDArray[], NDArray, bool)

MapIterGet(NDArray, NDArray[], NDArray, bool)'s body for one element type: normalizes and broadcasts the index arrays, computes the result's shape, then gathers — through the IL take kernel for one index array over a C-contiguous source (NumPy's mapiter_trivial_get: one typed move or one sub-array copy per index, read at the index array's own width), else by computing each selected position's element offset and copying one element (one index array per axis) or one sub-array per position (MapIterGetSubspace<T>(NDArray<T>, NDArray<long>, NDArray[], int, long[], long[], NDArray), or MapIterGetSubspaceStrided<T>(NDArray<T>, NDArray[], int, long[], long[], NDArray) for a source that is not C-contiguous).

protected static NDArray<T> FetchIndices<T>(NDArray<T> source, NDArray[] indices, NDArray @out, bool extraDim) where T : unmanaged

Parameters

source NDArray<T>

The array read, typed.

indices NDArray[]

The index arrays, as for MapIterGet(NDArray, NDArray[], NDArray, bool) (rewritten in place).

out NDArray

A destination of the result's shape and element type, or null.

extraDim bool

Not read.

Returns

NDArray<T>

The gathered array, or out. An EMPTY index array returns new NDArray<T>() without the selection's shape: the indexers resolve an empty selection before they get here.

Type Parameters

T

The element type of source's lane.

Remarks

Forwards to MapIterGet<T>(NDArray<T>, NDArray[], NDArray, bool) (moved there 2026-10-29); kept under its old name for types that derive from NDArray.

Exceptions

ArgumentNullException

source or indices is null.

ArgumentException

indices is empty, or out does not match.

IndexError

Too many index arrays, or an index value out of bounds.

IndexOutOfRangeException

The memory-safety backstop (a computed offset outside the buffer).

~NDArray()

Finalizer safety net: runs only when the user never called Dispose(). Drops this NDArray's reference via Abandon() — decrement WITHOUT the eager free-at-zero that Dispose() performs. This NDArray being unreachable proves nothing about OTHER reachable aliases of the same buffer (a bare UnmanagedStorage / IArraySlice obtained via GetData() holds no counted reference), so freeing here read as a use-after-free through such aliases. The memory block's own finalizer frees (and pools) the buffer in the GC cycle after the last alias dies.

protected ~NDArray()

FromMultiDimArray<T>(Array, bool)

Creates an NDArray out of given array of type T

public static NDArray FromMultiDimArray<T>(Array ndarray, bool copy = true) where T : unmanaged

Parameters

ndarray Array
copy bool

true for making

Returns

NDArray

Type Parameters

T

FromString(string)

Converts a string to a 1-D char array of its UTF-16 code units — NumSharp's character-vector view of text (the Char dtype), distinct from NumPy's fixed-width string dtypes: np.array("abc") is the 0-d <U3 array, NDArray.FromString("abc") the char vector ['a', 'b', 'c'].

public static NDArray FromString(string str)

Parameters

str string

The text.

Returns

NDArray

A new char vector (an empty string gives an empty vector).

Exceptions

ArgumentNullException

str is null.

GetAtIndex(long)

Reads the element at logical flat index index boxed as the dtype's own CLR type, after NumPy's flat-index check (a.item(i)).

public object GetAtIndex(long index)

Parameters

index long

The flat index (C order); a negative one counts from the end of the array.

Returns

object

The element, boxed.

Exceptions

IndexError

index is outside the array (NumPy's item texts; nothing outside the array is read).

GetAtIndex<T>(long)

Reads the element at logical flat index index as T: the stored value for the dtype's own type, NumPy's cast of it for any other T.

public T GetAtIndex<T>(long index) where T : unmanaged

Parameters

index long

The flat index (C order); a negative one counts from the end of the array.

Returns

T

The element as T.

Type Parameters

T

The type to read the element as.

Exceptions

IndexError

index is outside the array (NumPy's item texts; nothing outside the array is read).

GetBoolean(int[])

Reads the element at indices as a bool: the stored value in a bool array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public bool GetBoolean(int[] indices)

Parameters

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

bool

The element as a bool.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetBoolean(params long[])

Reads the element at indices as a bool: the stored value in a bool array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public bool GetBoolean(params long[] indices)

Parameters

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

bool

The element as a bool.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetByte(int[])

Reads the element at indices as a byte: the stored value in a uint8 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public byte GetByte(int[] indices)

Parameters

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

byte

The element as a byte.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetByte(params long[])

Reads the element at indices as a byte: the stored value in a uint8 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public byte GetByte(params long[] indices)

Parameters

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

byte

The element as a byte.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetChar(int[])

Reads the element at indices as a char: the stored value in a char array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public char GetChar(int[] indices)

Parameters

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

char

The element as a char.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetChar(params long[])

Reads the element at indices as a char: the stored value in a char array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public char GetChar(params long[] indices)

Parameters

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

char

The element as a char.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetComplex(int[])

Reads the element at indices as a Complex: the stored value in a complex128 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public Complex GetComplex(int[] indices)

Parameters

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

Complex

The element as a Complex.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetComplex(params long[])

Reads the element at indices as a Complex: the stored value in a complex128 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public Complex GetComplex(params long[] indices)

Parameters

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

Complex

The element as a Complex.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetData()

Get reference to internal data storage

public IArraySlice GetData()

Returns

IArraySlice

reference to internal storage as System.Array

GetData(int[])

Gets a NDArray at the single element addressed by the coordinate indices (one index per axis).

public NDArray GetData(int[] indices)

Parameters

indices int[]

The coordinates to the wanted value

Returns

NDArray

Remarks

Does not copy, returns a memory slice. This is the COORDINATE-ACCESS replacement for the old nd[new int[]{…}] behavior: a raw int[] as an index is now FANCY indexing (NumPy parity, selects rows), so use nd.GetData(coords) for the former element access.

GetData(long[])

Gets a NDArray at the single element addressed by the coordinate indices (one index per axis).

public NDArray GetData(long[] indices)

Parameters

indices long[]

The coordinates to the wanted value

Returns

NDArray

Remarks

Does not copy, returns a memory slice. This is the COORDINATE-ACCESS replacement for the old nd[new long[]{…}] behavior: a raw long[] as an index is now FANCY indexing (NumPy parity, selects rows), so use nd.GetData(coords) for the former element access.

GetData<T>()

Gets the internal storage and converts it to T if necessary.

public ArraySlice<T> GetData<T>() where T : unmanaged

Returns

ArraySlice<T>

An array of type T

Type Parameters

T

The returned type.

GetDecimal(int[])

Reads the element at indices as a decimal: the stored value in a decimal array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public decimal GetDecimal(int[] indices)

Parameters

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

decimal

The element as a decimal.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetDecimal(params long[])

Reads the element at indices as a decimal: the stored value in a decimal array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public decimal GetDecimal(params long[] indices)

Parameters

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

decimal

The element as a decimal.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetDouble(int[])

Reads the element at indices as a double: the stored value in a float64 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public double GetDouble(int[] indices)

Parameters

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

double

The element as a double.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetDouble(params long[])

Reads the element at indices as a double: the stored value in a float64 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public double GetDouble(params long[] indices)

Parameters

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

double

The element as a double.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetEnumerator()

Returns an enumerator that iterates along the first axis.

public IEnumerator GetEnumerator()

Returns

IEnumerator

Remarks

NumPy-compatible iteration behavior:

  • 0-D arrays (scalars): throws TypeError
  • 1-D arrays: yields scalar elements (a fixed-width string array yields string for U and byte[] for S, trailing NULs stripped — NumPy's np.str_ / np.bytes_ scalars)
  • N-D arrays (N > 1): yields (N-1)-D NDArray slices along first axis

GetHalf(int[])

Reads the element at indices as a Half: the stored value in a float16 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public Half GetHalf(int[] indices)

Parameters

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

Half

The element as a Half.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetHalf(params long[])

Reads the element at indices as a Half: the stored value in a float16 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public Half GetHalf(params long[] indices)

Parameters

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

Half

The element as a Half.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetHashCode()

NDArray is unhashable because it is mutable.

public override int GetHashCode()

Returns

int

Never returns - always throws.

Remarks

NumPy arrays are unhashable because they are mutable. If an array were used as a dictionary key and then modified, the hash would change, breaking the dictionary's invariants.

This matches NumPy behavior:

>>> hash(np.array([1, 2, 3]))
TypeError: unhashable type: 'numpy.ndarray'

Workarounds:

  • Use arr.tobytes() as a hashable key (immutable snapshot)
  • Use ReferenceEqualityComparer.Instance for identity-based dictionaries
  • Convert to tuple: tuple(arr.ToArray())

Exceptions

NotSupportedException

Always thrown.

GetIndices(NDArray, NDArray[])

NumPy's a[tuple(indices)]: the selection the indexer makes of an index tuple whose entries are these arrays, optionally copied into out.

public NDArray GetIndices(NDArray @out, NDArray[] indices)

Parameters

out NDArray

The array that receives the selection (np.copyto: the selection's shape must broadcast to it, its dtype be reachable under same_kind), or null for the selection itself.

indices NDArray[]

The index tuple's entries: integer index arrays (broadcast together, one per axis they index), boolean masks (each over as many leading axes as it has), 0-d integer arrays, a 0-d bool. An empty tuple selects the whole array (a[()]).

Returns

NDArray

The selection — a new array for an advanced index, a view for an empty tuple — or out when one is given.

Remarks

https://numpy.org/doc/stable/user/basics.indexing.html

Until 2026-10-29 the arrays reached the integer-array gather alone: a mask raised the IndexError for a non-integer index array, an empty tuple raised ArgumentException, and a 0-d array was read as a one-element 1-D array (no too-many-indices error, the wrong rank in the error texts).

Exceptions

ArgumentNullException

indices or one of its entries is null.

IndexError

The index does not fit this array (NumPy's prepare_index texts: a 0-d array indexed by an array is "too many indices for array: array is 0-dimensional, but 1 were indexed", a float index array is "arrays used as indices must be of integer (or boolean) type", an index out of bounds, index arrays that do not broadcast together, a mask that does not match its axes).

ValueError

out cannot receive the selection.

GetIndicesFromSlice(Shape, Slice, int)

Converts a slice to indices for the special case where slices are mixed with NDArrays in this[...]

protected static NDArray<long> GetIndicesFromSlice(Shape shape, Slice slice, int axis)

Parameters

shape Shape
slice Slice
axis int

Returns

NDArray<long>

GetIndicesFromSlice(long[], Slice, int)

Converts a slice to indices for the special case where slices are mixed with NDArrays in this[...]

protected static NDArray<long> GetIndicesFromSlice(long[] shape, Slice slice, int axis)

Parameters

shape long[]
slice Slice
axis int

Returns

NDArray<long>

GetInt16(int[])

Reads the element at indices as a short: the stored value in a int16 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public short GetInt16(int[] indices)

Parameters

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

short

The element as a short.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetInt16(params long[])

Reads the element at indices as a short: the stored value in a int16 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public short GetInt16(params long[] indices)

Parameters

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

short

The element as a short.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetInt32(int[])

Reads the element at indices as a int: the stored value in a int32 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public int GetInt32(int[] indices)

Parameters

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

int

The element as a int.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetInt32(params long[])

Reads the element at indices as a int: the stored value in a int32 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public int GetInt32(params long[] indices)

Parameters

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

int

The element as a int.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetInt64(int[])

Reads the element at indices as a long: the stored value in a int64 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public long GetInt64(int[] indices)

Parameters

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

long

The element as a long.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetInt64(params long[])

Reads the element at indices as a long: the stored value in a int64 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public long GetInt64(params long[] indices)

Parameters

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

long

The element as a long.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetNDArrays(int)

Get all NDArray slices at that specific dimension.

[SuppressMessage("ReSharper", "LoopCanBeConvertedToQuery")]
public NDArray[] GetNDArrays(int axis = 0)

Parameters

axis int

Zero-based dimension index on which axis and forward of it to select data., e.g. dimensions=1, shape is (2,2,3,3), returned shape = 4 times of (3,3)

Returns

NDArray[]

Examples

var nd = np.arange(27).reshape(3,1,3,3);
var ret = nd.GetNDArrays(1);
Assert.IsTrue(ret.All(n=>n.Shape == new Shape(3,3));
Assert.IsTrue(ret.Length == 3);
var nd = np.arange(27).reshape(3,1,3,3);

var ret = nd.GetNDArrays(0);
Assert.IsTrue(ret.All(n=>n.Shape == new Shape(1,3,3));
Assert.IsTrue(ret.Length == 3);

Remarks

Does not perform copy.

GetSByte(int[])

Reads the element at indices as a sbyte: the stored value in a int8 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public sbyte GetSByte(int[] indices)

Parameters

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

sbyte

The element as a sbyte.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetSByte(params long[])

Reads the element at indices as a sbyte: the stored value in a int8 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public sbyte GetSByte(params long[] indices)

Parameters

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

sbyte

The element as a sbyte.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetSingle(int[])

Reads the element at indices as a float: the stored value in a float32 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public float GetSingle(int[] indices)

Parameters

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

float

The element as a float.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetSingle(params long[])

Reads the element at indices as a float: the stored value in a float32 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public float GetSingle(params long[] indices)

Parameters

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

float

The element as a float.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetString(params long[])

Reads a vector of chars (the Char dtype) as one C# string: the innermost axis at the given outer coordinates. This is NumSharp's char-vector API, not NumPy element access: a fixed-width string array (U / S) stores one string per ELEMENT — read it with item(long) or AsStringArray(NDArray).

public string GetString(params long[] indices)

Parameters

indices long[]

The coordinates of the vector: one fewer than the array's rank.

Returns

string

A new string holding a copy of the vector's chars.

Remarks

Performs a copy due to String .net-framework limitations. NDAnchoredAttribute (lost-anchor site LT29): the string is allocated before the vector's chars are copied, so the array is rooted to the end — a temporary receiver could otherwise be collected, and its buffer freed, by a collection that the allocation triggers.

Exceptions

InvalidOperationException

The array is not a Char array (reading a U array's UCS-4 bytes as UTF-16 chars would return garbage), or the vector is longer than MaxValue chars.

ArgumentOutOfRangeException

indices does not address a vector.

GetStringAt(long)

GetString(params long[]) addressed by a flat offset of a char vector's element (its coordinates minus the innermost one select the vector).

public string GetStringAt(long offset)

Parameters

offset long

A flat element offset inside the vector to read.

Returns

string

A new string holding a copy of the vector's chars.

Remarks

Performs a copy due to String .net-framework limitations.

Exceptions

InvalidOperationException

The array is not a Char array.

GetUInt16(int[])

Reads the element at indices as a ushort: the stored value in a uint16 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public ushort GetUInt16(int[] indices)

Parameters

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

ushort

The element as a ushort.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetUInt16(params long[])

Reads the element at indices as a ushort: the stored value in a uint16 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public ushort GetUInt16(params long[] indices)

Parameters

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

ushort

The element as a ushort.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetUInt32(int[])

Reads the element at indices as a uint: the stored value in a uint32 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public uint GetUInt32(int[] indices)

Parameters

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

uint

The element as a uint.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetUInt32(params long[])

Reads the element at indices as a uint: the stored value in a uint32 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public uint GetUInt32(params long[] indices)

Parameters

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

uint

The element as a uint.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetUInt64(int[])

Reads the element at indices as a ulong: the stored value in a uint64 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public ulong GetUInt64(int[] indices)

Parameters

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

ulong

The element as a ulong.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetUInt64(params long[])

Reads the element at indices as a ulong: the stored value in a uint64 array, NumPy's cast of it (the cast astype runs) in an array of any other dtype.

public ulong GetUInt64(params long[] indices)

Parameters

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

ulong

The element as a ulong.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetValue(int[])

Reads the element at indices boxed as the dtype's own CLR type (a text element as its decoded C# value), after NumPy's coordinate check.

public object GetValue(int[] indices)

Parameters

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

object

The element, boxed.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetValue(params long[])

Reads the element at indices boxed as the dtype's own CLR type (a text element as its decoded C# value), after NumPy's coordinate check.

public object GetValue(params long[] indices)

Parameters

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

object

The element, boxed.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetValue<T>(int[])

Reads the element at indices as T: the stored value for the dtype's own type, NumPy's cast of it (the cast astype runs) for any other T.

public T GetValue<T>(int[] indices) where T : unmanaged

Parameters

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

T

The element as T.

Type Parameters

T

The type to read the element as.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

GetValue<T>(params long[])

Reads the element at indices as T: the stored value for the dtype's own type, NumPy's cast of it (the cast astype runs) for any other T.

public T GetValue<T>(params long[] indices) where T : unmanaged

Parameters

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out read their first element.

Returns

T

The element as T.

Type Parameters

T

The type to read the element as.

Exceptions

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is read).

MakeGeneric<T>()

Creates an independent typed view (alias) over this array's data without reallocating.

public NDArray<T> MakeGeneric<T>() where T : unmanaged

Returns

NDArray<T>

An independent typed view sharing this NDArray's data.

Type Parameters

T

The type of the generic; must equal dtype.

Remarks

The returned NDArray<TDType> shares the same underlying memory block but carries its own shape metadata (via Alias()), so reshaping, expanding or otherwise mutating its shape does NOT propagate back to this array — matching NumPy's ndarray.view() semantics. Element writes still affect the shared data. A fresh header is produced on every call, exactly like NumPy's view().

Exceptions

ArgumentException

When T != dtype

NanMax(NDAxis?, NDArray, bool, object, NDArray)

np.nanmax for this array's class: NumPy's nanmax tests type(a) is np.ndarray, and a base ndarray is np.fmax.reduce(a, axis=axis, out=out, **kwargs) - the engine's NanMax(NDArray, NDAxis?, bool, NDArray, object, NDArray), which reproduces NumPy's fmax schedules bit for bit. A subclass overrides this member with NumPy's branch for every other class (NDMatrix: _replace_nan, its own max, np.nan written back; NDCharArray: np.amax of itself).

protected virtual NDArray NanMax(NDAxis? axis, NDArray @out, bool keepdims, object initial, NDArray where)

Parameters

axis NDAxis?

The axis to reduce (negative counts from the end), a tuple of axes reduced together, or null for every axis.

out NDArray

NumPy's out=: the array that receives the result, or null.

keepdims bool

Whether the reduced axes stay with length one.

initial object

NumPy's initial=, or null; required with where.

where NDArray

NumPy's where= bool mask, or null.

Returns

NDArray

out itself when given (the caller's object, a matrix one included); otherwise a fresh array, a read-only 0-d one for a flat reduction without keepdims.

Remarks

[SubclassAware]: np.nanmax hands its operand straight to this member, so the subclass weave leaves the function alone and the override of the operand's class answers (C# virtual dispatch is NumPy's class test). Footgun: an array subclass that does not override it is computed as a base ndarray, where NumPy would take its subclass branch. The engine meets plain arrays only: a subclass out or where beside this plain operand goes in as its plain view, and the reduction's hand-back of that view returns the caller's object, as np.fmax.reduce(a, out=m) returns m. Because np.nanmax reaches it by plain virtual dispatch, a subclass declared outside NumSharp.dll is answered by its own override too (written there as protected override).

Exceptions

AxisError

axis (or an item of a tuple) is out of range.

ArgumentException

An empty reduction without initial (zero-size array to reduction operation fmax which has no identity); a non-bool mask.

ValueError

A read-only or misshapen out, a mask without initial, an initial the loop cannot hold.

OverflowError

An integer initial past the loop's range.

TypeError

Text, or a complex initial for a real loop.

IncorrectShapeException

The mask or out does not broadcast.

NanMin(NDAxis?, NDArray, bool, object, NDArray)

np.nanmin for this array's class: a base ndarray is np.fmin.reduce(a, axis=axis, out=out, **kwargs) (the engine's NanMin(NDArray, NDAxis?, bool, NDArray, object, NDArray)); a subclass overrides it with NumPy's branch for every other class, as for NanMax(NDAxis?, NDArray, bool, object, NDArray).

protected virtual NDArray NanMin(NDAxis? axis, NDArray @out, bool keepdims, object initial, NDArray where)

Parameters

axis NDAxis?

The axis to reduce (negative counts from the end), a tuple of axes reduced together, or null for every axis.

out NDArray

NumPy's out=: the array that receives the result, or null.

keepdims bool

Whether the reduced axes stay with length one.

initial object

NumPy's initial=, or null; required with where.

where NDArray

NumPy's where= bool mask, or null.

Returns

NDArray

out itself when given; otherwise a fresh array, a read-only 0-d one for a flat reduction without keepdims.

Remarks

[SubclassAware] for the reason of NanMax(NDAxis?, NDArray, bool, object, NDArray); like it, np.nanmin reaches the override of any subclass, one declared outside NumSharp.dll included (written there as protected override).

Exceptions

AxisError

axis (or an item of a tuple) is out of range.

ArgumentException

An empty reduction without initial (zero-size array to reduction operation fmin which has no identity); a non-bool mask.

ValueError

A read-only or misshapen out, a mask without initial, an initial the loop cannot hold.

OverflowError

An integer initial past the loop's range.

TypeError

Text, or a complex initial for a real loop.

IncorrectShapeException

The mask or out does not broadcast.

NormalizeIndexArray(NDArray)

Normalizes an index array for fancy indexing. NumPy accepts all integer types (int8/16/32/64, uint8/16/32/64) for indexing. Non-integer types (float, decimal, char, bool, the string classes) raise IndexError. We keep Int32/Int64 as-is; other integer types are converted to Int64.

protected static NDArray NormalizeIndexArray(NDArray indices)

Parameters

indices NDArray

The index array to normalize.

Returns

NDArray

The normalized index array (Int32 or Int64).

Remarks

An index-kind test (the INDEX's dtype, which NumPy's prepare_index tests too), so it stays with the indexers; protected internal since 2026-10-29 for the typed fetch and store (MapIterGet(NDArray, NDArray[], NDArray, bool) and MapIterSet(NDArray, NDArray[], NDArray)), which call it.

Exceptions

IndexError

When the index array is not an integer type: NumPy's IndexError and text (arrays used as indices must be of integer (or boolean) type). It used to be an IndexOutOfRangeException with that text; every other index path raises IndexError.

PrepareIndexGetters(Shape, NDArray[])

Generates index getter function based on given indices.

protected static Func<long, long>[] PrepareIndexGetters(Shape srcShape, NDArray[] indices)

Parameters

srcShape Shape

The shape to get indice from

indices NDArray[]

The indices trying to index.

Returns

Func<long, long>[]

One getter per index array: the k-th selected position's coordinate along that array's axis, wrapped into [0, dim).

Remarks

Reads each index array through a raw pointer (int64, else int32 — the two dtypes NormalizeIndexArray(NDArray) leaves), so the arrays must stay alive while the getters run. protected internal since 2026-10-29 for the typed fetch and store in Backends/Unmanaged/UnmanagedStorage.Mapping.cs, which call it.

Exceptions

IndexError

(From a getter, when called.) An index value outside [-dim, dim) for its axis, NumPy's text.

ReplaceData(IArraySlice)

Replaces this array's data buffer with the unmanaged slice values (no copy) of this array's current dtype. The shape is unchanged (an uninitialized array takes the slice's vector shape).

public void ReplaceData(IArraySlice values)

Parameters

values IArraySlice

The new data source; this array takes a counted reference on it.

Remarks

This array's counted reference moves from the old buffer to values (see MoveArcReference(IArraySlice)).

Exceptions

InvalidCastException

values is not a slice of this array's dtype.

ReplaceData(IArraySlice, Type)

Replaces this array's data buffer with the unmanaged slice values (no copy), switching the storage dtype to dtype. The shape is unchanged.

public void ReplaceData(IArraySlice values, Type dtype)

Parameters

values IArraySlice

The new data source; this array takes a counted reference on it.

dtype Type

The dtype this storage switches to (must match the slice's element type).

Remarks

This array's counted reference moves from the old buffer to values (see MoveArcReference(IArraySlice)) — a bare slice (e.g. from CloneData()) is thereby owned by this array and freed with it.

Exceptions

InvalidCastException

values is not a slice of dtype.

ReplaceData(NDArray)

Makes this array share nd's data — its buffer, shape and dtype. A sliced nd contributes a contiguous COPY of its window instead.

public void ReplaceData(NDArray nd)

Parameters

nd NDArray

The array whose data this array adopts.

Remarks

This array takes its OWN counted reference on the adopted buffer and releases the one it held on its old buffer (MoveArcReference(IArraySlice)). Before that, the storage swap left the reference on the old buffer — stranding it until a GC — while Dispose() released a reference on the adopted buffer that belonged to nd's owners: enough of those and the shared buffer was freed under a live nd.

Exceptions

ArgumentNullException

nd is null.

NotSupportedException

nd's dtype is not a NumSharp storage type.

ReplaceData(Array)

Replaces this array's data buffer with values, cast to this array's current dtype when their element type differs. The shape is unchanged (an uninitialized array takes the vector shape of values).

public void ReplaceData(Array values)

Parameters

values Array

The new data source (wrapped, not copied, unless a cast is needed).

Remarks

This array's counted reference moves from the old buffer to the new one (see MoveArcReference(IArraySlice)) — the old buffer is freed if this array was its last owner.

Exceptions

ArgumentNullException

values is null.

ReplaceData(Array, NPTypeCode)

Replaces this array's data buffer with values, switching the storage dtype to typeCode (casting values first when their element type differs). The shape is unchanged.

public void ReplaceData(Array values, NPTypeCode typeCode)

Parameters

values Array

The new data source (wrapped, not copied, unless a cast is needed).

typeCode NPTypeCode

The dtype this storage switches to.

Remarks

This array's counted reference moves from the old buffer to the new one (see MoveArcReference(IArraySlice)).

Exceptions

ArgumentNullException

values is null.

NotSupportedException

typeCode is not a NumSharp storage type.

ReplaceData(Array, Type)

Replaces this array's data buffer with values, switching the storage dtype to dtype (casting values first when their element type differs). The shape is unchanged — keeping it consistent with the new buffer's length is the caller's job.

public void ReplaceData(Array values, Type dtype)

Parameters

values Array

The new data source (wrapped, not copied, unless a cast is needed).

dtype Type

The dtype this storage switches to and the type values is cast to.

Remarks

This array's counted reference moves from the old buffer to the new one (see MoveArcReference(IArraySlice)) — the old buffer is freed if this array was its last owner.

Exceptions

ArgumentNullException

values is null.

NotSupportedException

dtype is not a NumSharp storage type.

Scalar(object)

Creates a 0-d NDArray holding value in the dtype of its own C# type — a NumPy scalar (a strong operand under NEP 50); a string is a U scalar, a byte[] an S one.

public static NDArray Scalar(object value)

Parameters

value object

The value of the scalar: a C# number, a string or a byte[].

Returns

NDArray

A new read-only 0-d array the caller owns: NumPy's scalar, which is immutable (see NumSharp.NDArray.PyArray_Return()).

Remarks

The result promotes like an array in every ufunc (uint8_array + NDArray.Scalar(300L) is int64); a C# literal operand is NumPy's weak Python scalar instead (uint8_array + 100 stays uint8). A write into the result raises NumPy's ValueError: assignment destination is read-only.

Exceptions

NotSupportedException

A value of a type NumSharp has no dtype for.

Scalar(object, DType)

Creates a 0-d NDArray holding value as dtype — a NumPy scalar of that dtype (np.float32(2.5)), a STRONG operand under NEP 50.

public static NDArray Scalar(object value, DType dtype)

Parameters

value object

The value of the scalar.

dtype DType

The dtype of the scalar — one descriptor parameter, like NumPy's dtype: a C# Type, an NPTypeCode, a NumPy dtype string ("f4") or a DType all convert implicitly.

Returns

NDArray

A new read-only 0-d array the caller owns: NumPy's scalar, which is immutable (see NumSharp.NDArray.PyArray_Return()).

Remarks

A numeric dtype converts value with Converts (C#'s conversions). A text dtype stores it as NumPy's setitem does: a fixed-width S / U dtype writes its text (a number's str(), cut to the width), and a NEP 55 StringDType stores it by stringdtype_setitem (np.array(5, dtype='T') is '5'; the NA object, or null for None, packs an NA element).

The result is read-only, as NumPy's scalar is: a write into it raises NumPy's ValueError: assignment destination is read-only. Code that needs a writable 0-d buffer allocates one (np.zeros(Shape.Scalar, dtype), np.array(x)).

The result promotes like an array in every ufunc: float32_array * NDArray.Scalar(2.0) is float64, as NumPy's float32_array * np.float64(2.0) is. A C# literal (float32_array * 2.0) is NumPy's weak Python scalar instead and keeps float32 (parity QA-05).

Exceptions

ArgumentNullException

dtype is null.

ValueError

A non-text value into a coerce=False StringDType.

UnicodeDecodeError

bytes that are not UTF-8 into a StringDType.

UnicodeEncodeError

A text with a lone surrogate into a StringDType, or non-ASCII text into S.

InvalidCastException

A value Converts cannot convert to the dtype.

Scalar<T>(object)

Creates a 0-d NDArray of T's dtype from value, converted to T when it is another type — a NumPy scalar, a STRONG operand under NEP 50.

public static NDArray Scalar<T>(object value) where T : unmanaged

Parameters

value object

The value of the scalar; a value of another type is converted with ChangeType<TOut>(object).

Returns

NDArray

A new read-only 0-d array the caller owns: NumPy's scalar, which is immutable (see NumSharp.NDArray.PyArray_Return()).

Type Parameters

T

The element type (one of the storage types).

Remarks

The result promotes like an array in every ufunc, as Scalar<T>(T)'s does, and is read-only like it.

Exceptions

InvalidCastException

A value Converts cannot convert to T.

Scalar<T>(T)

Creates a 0-d NDArray of T's dtype holding value — a NumPy scalar, a STRONG operand under NEP 50 (the library's computed scalars are built this way).

public static NDArray Scalar<T>(T value) where T : unmanaged

Parameters

value T

The value of the scalar.

Returns

NDArray

A new read-only 0-d array the caller owns: NumPy's scalar, which is immutable (see NumSharp.NDArray.PyArray_Return()).

Type Parameters

T

The element type (one of the storage types).

Remarks

The result promotes like an array in every ufunc: float16_array * NDArray.Scalar(0.5f) is float32. For an operand NumPy writes as a Python number (weak: it keeps the other operand's dtype), library code uses NumSharp.NDArray.PythonLiteral<T>(T), the 0-d array a C# literal becomes through the implicit conversion. A write into the result raises NumPy's ValueError: assignment destination is read-only; code that needs a writable 0-d buffer allocates one (new NDArray(typecode, Shape.Scalar)).

SetAtIndex(object, long)

Stores one boxed element at logical flat index index; the value must be the dtype's exact CLR type (an unboxing, never a conversion), null is Python's None.

public void SetAtIndex(object obj, long index)

Parameters

obj object

The element, boxed as the dtype's exact type, or null.

index long

The flat index (C order); a negative one counts from the end of the array.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

InvalidCastException

A non-null value that is not the dtype's exact CLR type.

IndexError

index is outside the array (NumPy's item texts; nothing outside the array is written).

SetAtIndex<T>(T, long)

Stores value at logical flat index index: as it is for the dtype's own type, cast to the dtype with NumPy's cast for any other T.

public void SetAtIndex<T>(T value, long index) where T : unmanaged

Parameters

value T

The value to store.

index long

The flat index (C order); a negative one counts from the end of the array.

Type Parameters

T

The value's type.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

index is outside the array (NumPy's item texts; nothing outside the array is written).

SetBoolean(bool, int[])

Stores value at indices: as it is in a bool array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a bool scalar).

public void SetBoolean(bool value, int[] indices)

Parameters

value bool

The value to store.

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetBoolean(bool, params long[])

Stores value at indices: as it is in a bool array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a bool scalar).

public void SetBoolean(bool value, params long[] indices)

Parameters

value bool

The value to store.

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetByte(byte, int[])

Stores value at indices: as it is in a uint8 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a uint8 scalar).

public void SetByte(byte value, int[] indices)

Parameters

value byte

The value to store.

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetByte(byte, params long[])

Stores value at indices: as it is in a uint8 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a uint8 scalar).

public void SetByte(byte value, params long[] indices)

Parameters

value byte

The value to store.

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetChar(char, int[])

Stores value at indices: as it is in a char array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a char scalar).

public void SetChar(char value, int[] indices)

Parameters

value char

The value to store.

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetChar(char, params long[])

Stores value at indices: as it is in a char array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a char scalar).

public void SetChar(char value, params long[] indices)

Parameters

value char

The value to store.

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetComplex(Complex, int[])

Stores value at indices: as it is in a complex128 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a complex128 scalar).

public void SetComplex(Complex value, int[] indices)

Parameters

value Complex

The value to store.

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetComplex(Complex, params long[])

Stores value at indices: as it is in a complex128 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a complex128 scalar).

public void SetComplex(Complex value, params long[] indices)

Parameters

value Complex

The value to store.

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetData(IArraySlice, int[])

public void SetData(IArraySlice value, int[] indices)

Parameters

value IArraySlice

The value to set

indices int[]

The

Remarks

Does not change internal storage data type.
If value does not match DType, value will be converted.

SetData(IArraySlice, params long[])

Set a IArraySlice at given indices(long[], DType) (long version).

public void SetData(IArraySlice value, params long[] indices)

Parameters

value IArraySlice

The value to set

indices long[]

The indices (long version)

Remarks

Does not change internal storage data type.
If value does not match DType, value will be converted.

SetData(NDArray, int[])

public void SetData(NDArray value, int[] indices)

Parameters

value NDArray

The value to set

indices int[]

The

Remarks

Does not change internal storage data type.
If value does not match DType, value will be converted.

SetData(NDArray, params long[])

Set a NDArray at given indices(long[], DType) (long version).

public void SetData(NDArray value, params long[] indices)

Parameters

value NDArray

The value to set

indices long[]

The indices (long version)

Remarks

Does not change internal storage data type.
If value does not match DType, value will be converted.

SetData(object, int[])

Set a NDArray, IArraySlice, Array or a scalar value at given indices(long[], DType).

public void SetData(object value, int[] indices)

Parameters

value object

The value to set

indices int[]

The

Remarks

Does not change internal storage data type.
If value does not match DType, value will be converted.

SetDecimal(decimal, int[])

Stores value at indices: as it is in a decimal array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a decimal scalar).

public void SetDecimal(decimal value, int[] indices)

Parameters

value decimal

The value to store.

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetDecimal(decimal, params long[])

Stores value at indices: as it is in a decimal array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a decimal scalar).

public void SetDecimal(decimal value, params long[] indices)

Parameters

value decimal

The value to store.

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetDouble(double, int[])

Stores value at indices: as it is in a float64 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a float64 scalar).

public void SetDouble(double value, int[] indices)

Parameters

value double

The value to store.

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetDouble(double, params long[])

Stores value at indices: as it is in a float64 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a float64 scalar).

public void SetDouble(double value, params long[] indices)

Parameters

value double

The value to store.

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetHalf(Half, int[])

Stores value at indices: as it is in a float16 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a float16 scalar).

public void SetHalf(Half value, int[] indices)

Parameters

value Half

The value to store.

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetHalf(Half, params long[])

Stores value at indices: as it is in a float16 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a float16 scalar).

public void SetHalf(Half value, params long[] indices)

Parameters

value Half

The value to store.

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetIndices(NDArray, NDArray[])

NumPy's a[tuple(indices)] = values: the indexer's store through an index tuple whose entries are these arrays.

public void SetIndices(NDArray values, NDArray[] indices)

Parameters

values NDArray

The value, stored by NumPy's assignment rules (broadcast to the selection; null is Python's None).

indices NDArray[]

The index tuple's entries, as for GetIndices(NDArray, NDArray[]): integer index arrays, boolean masks, 0-d arrays; an empty tuple stores into the whole array (a[()] = v).

Remarks

https://numpy.org/doc/stable/user/basics.indexing.html

    <p>Until 2026-10-29 the arrays reached the integer-array scatter alone: a mask raised the IndexError for a
    non-integer index array, an empty tuple raised <code>ArgumentException</code>, and a 0-d array was written as a
    one-element 1-D array where NumPy raises "too many indices".</p>

Exceptions

ArgumentNullException

indices or one of its entries is null.

ValueError

If this array is not writeable (e.g., broadcast array) — NumPy's "assignment destination is read-only", checked first — or the value does not fit the selection.

IndexError

The index does not fit this array (NumPy's prepare_index and MapIter texts, GetIndices(NDArray, NDArray[])).

OverflowError

A C# integer outside this array's integer dtype.

SetIndices(NDArray, NDArray[], NDArray)

The typed store an advanced index ends in (NumPy's mapiter_set, with mapiter_trivial_set's route for one index array): values, broadcast to the selection's shape (broadcast(index shapes) + src.shape[len(indices):]), written to the positions of src the integer index arrays name; a position named twice keeps the LAST write. Text into a numeric array is converted where NumPy converts it (MapIterSetFromText(NDArray, NDArray[], NDArray)); every other value is stored by src's storage lane through MapIterSet<T>(NDArray<T>, NDArray[], NDArray).

protected static void SetIndices(NDArray src, NDArray[] indices, NDArray values)

Parameters

src NDArray

The array written (writeability is the caller's check).

indices NDArray[]

One integer index array per leading axis, as for MapIterGet(NDArray, NDArray[], NDArray, bool) (REWRITTEN in place with their normalized forms).

values NDArray

The value: a C# literal (NumPy's Python scalar, packed with NumPy's range checks) or an array broadcast to the selection by NumPy's MapIter rule (leading axes beyond the selection's rank must hold one element in total).

Remarks

[NDScoped] (nothing escapes a store): the per-dispatch MakeGeneric alias, the offsets buffer and the broadcast / materialized value temporaries are released when the call returns, exceptions included; src and values were made outside and are never touched.

Exceptions

ArgumentNullException

src or indices is null.

ArgumentException

indices is empty.

IndexError

More index arrays than src has axes, or an index value out of bounds (NumPy's texts; the one-index-array route checks every index before its first write).

ValueError

The value does not broadcast to the selection (NumPy's "shape mismatch: value array of shape ... could not be broadcast to indexing result of shape ..." and "could not broadcast input array from shape ... into shape ..."), or a text value does not parse into the dtype.

OverflowError

A C# integer literal, or an integer text, outside the dtype.

IndexOutOfRangeException

The memory-safety backstop (a computed offset outside a buffer).

NotSupportedException

A text lane: a fixed-width or StringDType array has no typed store here (the indexers run its index on a unit view or on marks).

SetIndices(object[], NDArray)

protected void SetIndices(object[] indicesObjects, NDArray values)

Parameters

indicesObjects object[]
values NDArray

SetIndicesNDNonLinear<T>(NDArray<T>, NDArray[], int, long[], long[], NDArray<T>)

Subshaped fancy scatter (ndsCount < dst.ndim) into a NON-contiguous destination (transposed / row- or col-strided / negative-stride / F-contig). The contiguous fast path (MapIterSetSubspace<T>(NDArray<T>, NDArray<long>, NDArray[], int, long[], long[], NDArray<T>)) block-copies one CONTIGUOUS subShape per selected offset, but a strided destination's sub-arrays are not contiguous in the buffer, so scatter element-by-element through the destination strides from the C-contiguous (already broadcast to retShape) value buffer. Exact scatter mirror of the getter's MapIterGetSubspaceStrided: same odometer over the trailing subShape axes, only the copy direction is reversed. NumPy likewise assigns a scalar / lower-rank / broadcast value into a strided destination through the view's own strides.

protected static void SetIndicesNDNonLinear<T>(NDArray<T> dst, NDArray[] indices, int ndsCount, long[] retShape, long[] subShape, NDArray<T> values) where T : unmanaged

Parameters

dst NDArray<T>

Destination array (a non-contiguous view aliasing the base buffer).

indices NDArray[]

One flat integer index array per consumed leading axis (broadcast together).

ndsCount int

Number of leading axes the indices consume (< dst.ndim).

retShape long[]

Indexing-result shape (num_offsets,) + subShape; the value's shape.

subShape long[]

The trailing (untouched) axes each selected offset writes across.

values NDArray<T>

Value buffer, C-contiguous and exactly retShape.

Type Parameters

T

The element type.

Remarks

An empty trailing axis or an empty index array writes nothing.

Exceptions

IndexError

An index value out of bounds (from PrepareIndexGetters(Shape, NDArray[])'s getters).

IndexOutOfRangeException

An element outside the destination's or the value's buffer: the memory-safety guard.

SetIndicesND<T>(NDArray<T>, NDArray<long>, NDArray[], int, long[], long[], NDArray<T>)

The subspace scatter of mapiter_set for a C-contiguous destination: each selected position's sub-array (the axes the index arrays leave, subShape) is ONE contiguous block there, written whole at the precomputed element offset from the value — in order from a contiguous value, through the value's own strides otherwise. Use only when the destination is C-contiguous; a strided destination's sub-arrays are not blocks (MapIterSetSubspaceStrided<T>(NDArray<T>, NDArray[], int, long[], long[], NDArray<T>)).

protected static void SetIndicesND<T>(NDArray<T> dst, NDArray<long> dstOffsets, NDArray[] dstIndices, int ndsCount, long[] retShape, long[] subShape, NDArray<T> values) where T : unmanaged

Parameters

dst NDArray<T>

The C-contiguous destination; the offsets index its buffer, its view offset included.

dstOffsets NDArray<long>

One element offset per selected position (1-D), from the index arrays.

dstIndices NDArray[]

Not read (the index arrays the offsets came from).

ndsCount int

Not read (the number of leading axes the index arrays consume).

retShape long[]

The selection's shape (named by the guard's message only).

subShape long[]

The trailing axes each position writes.

values NDArray<T>

The value, already broadcast to the selection: one subShape block per offset.

Type Parameters

T

The element type.

Remarks

Forwards to MapIterSetSubspace<T>(NDArray<T>, NDArray<long>, NDArray[], int, long[], long[], NDArray<T>) (moved there 2026-10-29); kept under its old name for types that derive from NDArray.

Exceptions

IndexOutOfRangeException

A block outside the destination's or the value's buffer: the memory-safety guard (a miscomputed shape would otherwise write past a pinned buffer).

SetIndices<T>(NDArray<T>, NDArray[], NDArray)

MapIterSet(NDArray, NDArray[], NDArray)'s body for one element type, in NumPy's order: the too-many-indices check, the value's packing (a C# literal, PyArray_Pack's range checks) BEFORE any index value is read, the index arrays' normalization and broadcast, the selection's shape, the value prepared against it (PrepareAssignedValue(NDArray, long[]), MapIter's value rule), then the scatter — the IL put kernel for one index array into a C-contiguous destination (TryScatterKernel<T>(NDArray<T>, Shape, void*, bool, long, long, long, long[], long[], bool, NDArray): every index checked before the first write, as mapiter_trivial_set does), else by each selected position's element offset, one element (one index array per axis) or one sub-array per position (MapIterSetSubspace<T>(NDArray<T>, NDArray<long>, NDArray[], int, long[], long[], NDArray<T>), or MapIterSetSubspaceStrided<T>(NDArray<T>, NDArray[], int, long[], long[], NDArray<T>) for a destination that is not C-contiguous).

protected static void SetIndices<T>(NDArray<T> source, NDArray[] indices, NDArray values) where T : unmanaged

Parameters

source NDArray<T>

The array written, typed.

indices NDArray[]

The index arrays (rewritten in place).

values NDArray

The value, as for MapIterSet(NDArray, NDArray[], NDArray).

Type Parameters

T

The element type of source's lane.

Remarks

An EMPTY index array returns before anything is written, but after the value's packing: an empty selection stores nothing, and an out-of-range literal still raises, as in NumPy.

Exceptions

ArgumentNullException

source or indices is null.

ArgumentException

indices is empty.

IndexError

Too many index arrays, or an index value out of bounds.

ValueError

The value does not broadcast to the selection.

OverflowError

A C# integer literal outside T.

IndexOutOfRangeException

The memory-safety backstop.

SetInt16(short, int[])

Stores value at indices: as it is in a int16 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a int16 scalar).

public void SetInt16(short value, int[] indices)

Parameters

value short

The value to store.

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetInt16(short, params long[])

Stores value at indices: as it is in a int16 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a int16 scalar).

public void SetInt16(short value, params long[] indices)

Parameters

value short

The value to store.

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetInt32(int, int[])

Stores value at indices: as it is in a int32 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a int32 scalar).

public void SetInt32(int value, int[] indices)

Parameters

value int

The value to store.

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetInt32(int, params long[])

Stores value at indices: as it is in a int32 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a int32 scalar).

public void SetInt32(int value, params long[] indices)

Parameters

value int

The value to store.

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetInt64(long, int[])

Stores value at indices: as it is in a int64 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a int64 scalar).

public void SetInt64(long value, int[] indices)

Parameters

value long

The value to store.

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetInt64(long, params long[])

Stores value at indices: as it is in a int64 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a int64 scalar).

public void SetInt64(long value, params long[] indices)

Parameters

value long

The value to store.

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetSByte(sbyte, int[])

Stores value at indices: as it is in a int8 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a int8 scalar).

public void SetSByte(sbyte value, int[] indices)

Parameters

value sbyte

The value to store.

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetSByte(sbyte, params long[])

Stores value at indices: as it is in a int8 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a int8 scalar).

public void SetSByte(sbyte value, params long[] indices)

Parameters

value sbyte

The value to store.

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetSingle(float, int[])

Stores value at indices: as it is in a float32 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a float32 scalar).

public void SetSingle(float value, int[] indices)

Parameters

value float

The value to store.

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetSingle(float, params long[])

Stores value at indices: as it is in a float32 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a float32 scalar).

public void SetSingle(float value, params long[] indices)

Parameters

value float

The value to store.

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetString(string, params long[])

Writes a C# string's UTF-16 chars into a vector of chars (the Char dtype) at the given outer coordinates — NumSharp's char-vector API. A fixed-width string array (U / S) takes a string per ELEMENT through its indexer (a[i] = "text", truncated to the element width like NumPy).

public void SetString(string value, params long[] indices)

Parameters

value string

The text (its chars are copied from the vector's start; a longer text writes past the vector's end only within the buffer the coordinates address, so keep it within the innermost length).

indices long[]

The coordinates of the vector: one fewer than the array's rank.

Exceptions

InvalidOperationException

The array is not a Char array.

ArgumentException

value is null or empty.

ArgumentOutOfRangeException

indices does not address a vector.

ValueError

The array is read-only.

SetStringAt(string, long)

SetString(string, params long[]) addressed by a flat offset of a char vector's element.

public void SetStringAt(string value, long offset)

Parameters

value string

The text.

offset long

A flat element offset inside the vector to write.

Exceptions

InvalidOperationException

The array is not a Char array.

ArgumentException

value is null or empty.

ValueError

The array is read-only.

SetUInt16(ushort, int[])

Stores value at indices: as it is in a uint16 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a uint16 scalar).

public void SetUInt16(ushort value, int[] indices)

Parameters

value ushort

The value to store.

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetUInt16(ushort, params long[])

Stores value at indices: as it is in a uint16 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a uint16 scalar).

public void SetUInt16(ushort value, params long[] indices)

Parameters

value ushort

The value to store.

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetUInt32(uint, int[])

Stores value at indices: as it is in a uint32 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a uint32 scalar).

public void SetUInt32(uint value, int[] indices)

Parameters

value uint

The value to store.

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetUInt32(uint, params long[])

Stores value at indices: as it is in a uint32 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a uint32 scalar).

public void SetUInt32(uint value, params long[] indices)

Parameters

value uint

The value to store.

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetUInt64(ulong, int[])

Stores value at indices: as it is in a uint64 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a uint64 scalar).

public void SetUInt64(ulong value, int[] indices)

Parameters

value ulong

The value to store.

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetUInt64(ulong, params long[])

Stores value at indices: as it is in a uint64 array, cast to the array's dtype with NumPy's cast in an array of any other dtype (NumPy's setitem of a uint64 scalar).

public void SetUInt64(ulong value, params long[] indices)

Parameters

value ulong

The value to store.

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetValue(object, int[])

Stores one boxed element at indices; the value must be the dtype's exact CLR type (an unboxing, never a conversion; the generic overload converts), null is Python's None.

public void SetValue(object value, int[] indices)

Parameters

value object

The element, boxed as the dtype's exact type, or null.

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

InvalidCastException

A non-null value that is not the dtype's exact CLR type.

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetValue(object, params long[])

Stores one boxed element at indices; the value must be the dtype's exact CLR type (an unboxing, never a conversion; the generic overload converts), null is Python's None.

public void SetValue(object value, params long[] indices)

Parameters

value object

The element, boxed as the dtype's exact type, or null.

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out address their first element.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

InvalidCastException

A non-null value that is not the dtype's exact CLR type.

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetValue<T>(T, int[])

Stores value at indices: as it is for the dtype's own type, cast to the dtype with NumPy's cast (the cast astype runs) for any other T.

public void SetValue<T>(T value, int[] indices) where T : unmanaged

Parameters

value T

The value to store.

indices int[]

One coordinate per leading axis; a negative coordinate counts from the end of its axis, and axes left out address their first element.

Type Parameters

T

The value's type.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

SetValue<T>(T, params long[])

Stores value at indices: as it is for the dtype's own type, cast to the dtype with NumPy's cast (the cast astype runs) for any other T.

public void SetValue<T>(T value, params long[] indices) where T : unmanaged

Parameters

value T

The value to store.

indices long[]

One coordinate per leading axis (long version); a negative coordinate counts from the end of its axis, and axes left out address their first element.

Type Parameters

T

The value's type.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing outside the array is written).

ToArray<T>()

Copies this array into a new single-dimensional .NET array of element type T, in logical C (row-major) order for any memory layout and any rank. A 0-d array yields a one-element array.

public T[] ToArray<T>() where T : unmanaged

Returns

T[]

A freshly allocated array of size elements that shares no memory with this NDArray (an empty result is the shared, immutable Empty<T>() instance).

Type Parameters

T

Element type of the result. When it differs from dtype, the values are converted exactly as astype(DType, bool) converts them; it must be one of NumSharp's 15 dtypes.

Remarks

One pass, straight into the result: flat + a block copy is the two-pass form of this method (materialize a C-order image, then copy it); here the pinned result itself is the destination and no intermediate buffer exists. A C-contiguous source (any offset) is the block copy alone.

Dedicated paths for everything the plain copy does not cover. Exact copies: one element (a direct copy), a scalar broadcast (one fill), and every other non-contiguous layout through ToArrayDedicated<T>(T*, long[], long[], T*), a layout-specific fill engine that replaced the iterator copy — per layout class it measured faster than the iterator's generic walk (transposes by register blocks or 64-column bands — a large float64-width one streamed into the result by whole 64-byte lines where its row pitch allows it —, strided rows by AVX2 deinterleave / gathers, reversed rows by a vector reverse, permuted views transposed over their unit-stride axis; a reversed run of at least a mebibyte streamed into the result by whole 64-byte lines on non-temporal stores, assembled in registers — or, for a plane of rows shorter than 16 KB, packed through an L1-resident scratch; a rank-2 view is canonicalized in registers, ToArrayPlane2D<T>(T*, long, long, long, long, T*)). Conversions: a contiguous source of one of 24 common pairs through this file's AVX2 converters (ToArrayConvertVectors<T>(byte*, T*, long, NPTypeCode)), any other through the generator's cast kernel for the pair in one call (or the bit-exact decimal → double vector kernel; a result of at least a mebibyte of one of seven common pairs converted in registers straight into whole 64-byte lines on non-temporal stores, ToArrayConvertLines<T>(byte*, T*, long, NPTypeCode)); a pair without a kernel, or any other layout, up to NumSharp.NDArray.ToArrayGatherMaxElements elements through a scalar odometer converting element by element with astype's scalar converter; larger ones keep astype's copy core (the iterator's cast copy).

A large-object result (from NumSharp.NDArray.ToArrayLargeObjectBytes) is fresh from the OS and faults in on first touch. A fill that writes the C-order result out of address order (a transpose) would take those faults inside its walk, each evicting the walk's cache working set; such results have their pages faulted in first, in address order, by a tight pre-pass (ToArrayTouchPages(byte*, long)) — measured on a 1000×1000 float64 transpose: ≈ 1.9 ms → ≈ 1.3 ms. A sequential fill skips it (there it measured +8 %).

Four frames, each shaped for the fixed cost of the calls it serves. This one holds only the hot case — a C-contiguous source of the same dtype: one allocation and one block copy (a result of at most 64 bytes copied inline, ToArrayCopySmall(byte*, ref byte, int)) — behind one type-code compare, so a tiny contiguous call pays for nothing else. Every other same-dtype case leaves for NumSharp.NDArray.ToArrayExact<T>(), every conversion (a T with no NumSharp dtype included) for NumSharp.NDArray.ToArrayConverted<T>(), each ONE [NoInlining] frame. The conversion frame runs only the common small conversion — a C-contiguous source whose pair already has a remembered cast kernel: one allocation, one kernel call — and hands everything else to NumSharp.NDArray.ToArrayConvertedGeneral<T>(), which reads its target from InfoOf<T> (a JIT-time constant there, so the inlined scalar converter folds to one arm) and fills the per-(T, source dtype) kernel cache (ToArrayCastKernel<T>(NPTypeCode)) the conversion frame reads.

NDAnchoredAttribute: every frame copies from this array's storage address, and the storage does not hold the buffer (this array's ARC reference does), so a receiver the caller built as a temporary (np.arange(n).ToArray<long>()) could be collected mid-copy. The weaver roots this until the copy returns; the root emits no code, so the hot frame keeps its shape.

Exceptions

NotSupportedException

T is not a NumSharp dtype.

InvalidOperationException

The array holds more than MaxValue elements, which no .NET array can index.

ToJaggedArray<T>()

Copies this array into a fresh .NET jagged array (T[] for 1-D, T[][] for 2-D, …, one nesting level per dimension, any rank), reading the logical elements in C order whatever the memory layout (C/F-contiguous, transposed, strided, reversed, offset or broadcast views).

public Array ToJaggedArray<T>() where T : unmanaged

Returns

Array

A new jagged array, statically typed as Array; cast it to the nested type (e.g. (double[][])). Every sub-array is a distinct object, and nothing is shared with this array.

Type Parameters

T

Element type of the result. When it differs from this array's dtype, the values are converted exactly as astype(DType, bool) converts them. A type that is not a NumSharp dtype is refused the same way astype refuses it.

Remarks

The work is allocation-shaped: the only per-element cost is one read and one write (a conversion when T differs from the dtype), and no temporary array is ever allocated. Each leaf's fixed cost is kept to its allocation:

The levels above the blocks (rank ≥ 3) are built by an IL-emitted, rank-specialised method: one per (T, rank, exact-or-converted), compiled on first use and cached. Each level is allocated with its exact nested type (newarr) and stored with a typed stelem, so there is no per-call MakeArrayType, Array.CreateInstance or covariant store. Runtimes that cannot compile dynamic code fall back to a recursive descent with reflection-created levels and the same results. The pointer follows the source's own strides, so every layout is read in place.

NDAnchoredAttribute: the fill reads this array's storage address, and the storage does not hold the buffer (this array's ARC reference does), so a receiver the caller built as a temporary could be collected mid-copy. The weaver roots this until the copy returns.

Exceptions

InvalidOperationException

This array is 0-d (a scalar has no jagged form), or a dimension exceeds MaxValue (managed arrays are int-indexed).

NotSupportedException

T is not one of NumSharp's dtypes (raised by astype itself, so the exception is exactly the one astype raises).

ToMuliDimArray<T>()

Copies this array into a new .NET array of element type T: a single-dimensional T[] for a 0-d or 1-D array (a 0-d array yields a one-element array, since .NET has no rank-0 array), otherwise a rank-N T[,…] with the same lengths. Elements are written in logical C (row-major) order for any memory layout.

public Array ToMuliDimArray<T>() where T : unmanaged

Returns

Array

A freshly allocated managed array that shares no memory with this NDArray.

Type Parameters

T

Element type of the result. When it differs from dtype the values are converted with astype(DType, bool) semantics; it must be one of NumSharp's 15 dtypes.

Remarks

One pass straight into the pinned result, lean where it is hot: the shape is read by reference, a large 1-D result is allocated uninitialized on the pinned-object heap, a contiguous same-dtype source is one memcpy (one assignment for one element) from the logical start, and a one-element conversion is one inline scalar conversion. Only the multi-element conversion setup is outlined ([NoInlining] ConvertInto<T>(T*, NPTypeCode)), so it adds nothing to this frame. Rank ≥ 4 allocates through NDArray.RankNAllocator<T> (IL newobj, no reflection-driven activation). The fill engine is the parent's: same dtype + non-contiguous goes through CopyStrided<T>(T*, long[], long[], T*) (row memcpy for unit inner stride, 64-column bands walked in 8-row strips of AVX register blocks for transposed / F-ordered planes, AVX2 stride-2 deinterleave or gathers for plain strided rows of 4/8-byte elements, an indexed scalar loop otherwise); a multi-element conversion is ConvertInto<T>(T*, NPTypeCode) — astype's cast kernels, or NDArray.DecimalToDoubleKernel for a contiguous decimal → double where its probe proved it bit-identical.

NDAnchoredAttribute: the fill reads Storage.Address with no later use of this array, so a receiver the caller built as a temporary could be collected (and its buffer pooled) mid-copy — the lifetime oracle's gap LT27. The weaver roots this until the copy returns.

Exceptions

NotSupportedException

T is not a NumSharp dtype.

InvalidOperationException

A dimension exceeds MaxValue (managed arrays are int-indexed).

TypeLoadException

The array has more than 32 dimensions, the .NET limit on array rank.

ToString()

Returns the NumPy str() representation of this array (equivalent to np.array_str), e.g. [1 2 3].

public override string ToString()

Returns

string

Remarks

Matches NumPy 2.4.2 exactly: space separators, decimal-point alignment for floats, summarization at threshold, and line wrapping at linewidth. Use ToString(bool) with flat: true for the repr() form (array([1, 2, 3], dtype=…)).

ToString(bool)

Returns the array as a string. When flat is false this is the NumPy str() form (np.array_str); when true it is the NumPy repr() form (np.array_repr, i.e. array([…], dtype=…)).

public string ToString(bool flat)

Parameters

flat bool

Returns

string

__array_finalize__(DType)

The dtype check of this class's array_finalize, run where NumPy creates a result of the class BEFORE computing it (np.zeros_like(c, dtype)) or for a result that is a C# number (np.argmax(c)'s index, created as the class before PyArray_Return). An ndarray checks nothing.

protected virtual void __array_finalize__(DType dtype)

Parameters

dtype DType

The dtype of the result about to be created.

Remarks

A subclass whose finalize rule depends on the dtype overrides it to throw before any work is done (from another assembly the override is protected override); the woven dispatch reaches it only for NDMatrix and NDCharArray today.

Exceptions

ValueError

An override refuses the dtype (a chararray of a dtype that is not string data: Can only create a chararray from string data.).

__array_finalize__(NDArray, bool, NewSubtypeZeroDim)

NumPy's subtype creation: the result allocated as this array's class (Py_TYPE(self)), then the class's array_finalize run on it. C# cannot retype an object, so the plain result goes in and the result as the class comes out; an ndarray's is the result itself.

protected virtual NDArray __array_finalize__(NDArray created, bool keepRank, NewSubtypeZeroDim zeroDim)

Parameters

created NDArray

The result NumPy creates as this class, computed plain.

keepRank bool

NumPy indexed a matrix with a new axis (matrix.getitem switches its finalize rule off), so the result keeps its rank.

zeroDim NewSubtypeZeroDim

How a 0-d result reaches the caller (a chararray's element stand-in).

Returns

NDArray

The result as this class; created itself for an ndarray.

Remarks

A subclass overrides it to build itself over created and apply its own finalize rule (from another assembly the override is protected override). The woven dispatch reaches it only for NDMatrix and NDCharArray today.

Exceptions

ValueError

An override's finalize rule refuses the result (a matrix of more than two axes longer than 1; a chararray of a dtype that is not string data).

__array_wrap__(NDArray)

NumPy's ndarray.array_wrap(array): array as this array's class (an ndarray's wrap of a plain array is the array itself). The woven subclass path calls it on the operand npy_find_array_wrap chose, with the result computed on the plain views.

protected virtual NDArray __array_wrap__(NDArray array)

Parameters

array NDArray

The result to wrap (a plain array, or the caller's operand handed back).

Returns

NDArray

array itself for an ndarray; the class's view of it in an override.

Remarks

A subclass overrides it to return its own view of array (from another assembly the override is protected override). Footgun: the woven dispatch calls it only for NDMatrix and NDCharArray operands today, so a subclass declared outside NumSharp.dll still gets plain results from np.* functions.

Exceptions

ValueError

An override's finalize rule refuses the result (a matrix of more than two axes longer than 1).

__contains__(object)

Python-compatible contains method. Equivalent to Contains(object).

public bool __contains__(object value)

Parameters

value object

Value to search for.

Returns

bool

True if value exists in the array.

Remarks

This method exists for Python interoperability and naming consistency. In Python: value in arr calls arr.contains(value)

__getitem__(object)

NumPy's ndarray.getitem(key, /): the same as a[key] (this[object[]]).

public NDArray __getitem__(object key)

Parameters

key object

The index, as Python passes it to getitem: one entry (an integer, a slice-notation string such as "1:3" or "..., 0", a Slice, an index array, a mask, a C# bool) or the whole index tuple — an object[] / Slice[] (each element an entry) or a C# tuple (a.getitem((1, "0:2"))). A typed C# array other than Slice[] (int[], bool[]) is ONE entry, NumPy's list: an index array or a mask.

Returns

NDArray

The selection: a view for an index of integers and slices (0-d for one integer per axis), a new array for an advanced index.

Remarks

One member, NumPy's signature. An integer array used to bind a params int[] form that read it as COORDINATES (a.getitem(1, 2)); NumPy reads a list key as an index array, and so does this member — pass a tuple for coordinates (a.getitem((1, 2))).

Exceptions

ArgumentNullException

key is null (NumPy's a[None] is NewAxis).

IndexError

The index is invalid for this array (NumPy's prepare_index texts).

__hash__()

Python-compatible hash method. NDArray is unhashable because it is mutable.

public int __hash__()

Returns

int

Never returns - always throws.

Remarks

This method exists for Python interoperability and naming consistency. In Python: hash(arr) calls arr.hash()

NumPy behavior:

>>> arr = np.array([1, 2, 3])
>>> hash(arr)
TypeError: unhashable type: 'numpy.ndarray'

Exceptions

NotSupportedException

Always thrown.

__iter__()

Python-compatible iter method. Returns an enumerator over the first axis.

public IEnumerator __iter__()

Returns

IEnumerator

Enumerator yielding NDArray slices along the first axis.

Remarks

This matches NumPy behavior:

>>> for row in np.array([[1, 2], [3, 4]]):
...     print(row)
[1 2]
[3 4]

For 1-D arrays, iterates over scalar elements. For N-D arrays, iterates over (N-1)-D slices.

__len__()

Python-compatible len method. Returns the length of the first dimension (like Python's len()).

public long __len__()

Returns

long

Length of the first dimension, or 1 for scalars.

Remarks

This matches NumPy behavior:

>>> len(np.array([1, 2, 3]))
3
>>> len(np.array([[1, 2], [3, 4]]))
2  # First dimension
>>> len(np.array(5))
TypeError: len() of unsized object

Note: For scalars (0-d arrays), NumPy raises TypeError: len() of unsized object and NumSharp raises the same, message-verbatim (oracle-gated by the instance tier). Use size for total element count.

__setitem__(object, object)

NumPy's ndarray.setitem(key, value, /): stores exactly what a[key] = value stores, for any value kind (the indexer's setter takes an NDArray).

public void __setitem__(object key, object value)

Parameters

key object

The index, as for __getitem__(object).

value object

Value to set — an NDArray, a C# scalar (NumPy's Python scalar), a C# array or list, or null (Python's None); see SetItemValue(object).

Exceptions

ArgumentNullException

key is null.

IndexError

The index is invalid for this array (NumPy's texts).

TypeError

value is null (Python's None) and this is an integer (or decimal) array: int(None)'s text, after the index's bounds check. A float array stores NaN, complex nan+nanj, bool False, text 'None' or a StringDType NA object.

OverflowError

A C# integer outside this array's integer dtype (NumPy's OverflowError).

ValueError

The array is read-only, the value does not broadcast to the selection, or does not parse into its dtype.

_collapse(NDArray, NDAxis?)

numpy.matrix's _collapse(axis) after a keepdims=True reduction, applied to the plain reduction NumPy's function computed (np.nansum(m) is np.sum of the nan-replaced matrix). An ndarray has no _collapse.

protected virtual NDArray _collapse(NDArray result, NDAxis? axis)

Parameters

result NDArray

The plain reduction (keepdims=False), unaliased.

axis NDAxis?

The caller's axis: null for None, an int (it decides row or column for a 1-d plain result), or a tuple (NumPy keeps every axis it names with length 1, the empty tuple included).

Returns

NDArray

null: this class has no _collapse (the reduction keeps NumPy's other answer).

Remarks

Returning non-null claims the reduction's result for the class: only a subclass that collapses like numpy.matrix should override it (from another assembly as protected override). The axis became NumPy's axis type with API-parity batch 5 (a breaking change for such an override, which took int?), so a tuple reaches the class instead of reading as None.

all(int, NDArray, bool, NDArray)

all(NDAxis?, NDArray, bool, NDArray) with the axis as one int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so every answer, error, layout and subclass result is that overload's.

public NDArray all(int axis, NDArray @out = null, bool keepdims = false, NDArray where = null)

Parameters

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

out NDArray

An array of the result's shape and any dtype to store the result in (and return); null for a fresh bool array. A C# scalar here is NumPy's TypeError (return arrays must be of ArrayType).

keepdims bool

If true, the reduced axes are left in the result as dimensions with size one.

where NDArray

A bool mask of the elements to include (it broadcasts to this array's shape); null includes all.

Returns

NDArray

out itself when given; otherwise a fresh bool array, read-only when 0-d (NumPy's scalar).

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.all.html. NumSharp's static-typing rule ([PlainReceiver]): called on a numpy.matrix through an NDArray reference it computes as the plain array (the matrix's own all is all(NDAxis?, NDArray)). The axis is an NDAxis since API-parity batch 4 (2026-11-12); an int? argument converts.

Exceptions

AxisError

An axis is out of bounds.

ValueError

A tuple names an axis twice (duplicate value in 'axis'), or a read-only or misshapen out / where (NumPy's reduction texts).

IncorrectShapeException

where or out does not broadcast against this array.

TypeError

out is a C# scalar.

all(int[], NDArray, bool, NDArray)

all(NDAxis?, NDArray, bool, NDArray) with the axes as an int[]: the overload an int[] binds, and a bare null too (null converts to int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple (new int[0] is ()).

public NDArray all(int[] axis, NDArray @out = null, bool keepdims = false, NDArray where = null)

Parameters

axis int[]

The axes as NumPy's tuple, or null for None.

out NDArray

An array of the result's shape and any dtype to store the result in (and return); null for a fresh bool array. A C# scalar here is NumPy's TypeError (return arrays must be of ArrayType).

keepdims bool

If true, the reduced axes are left in the result as dimensions with size one.

where NDArray

A bool mask of the elements to include (it broadcasts to this array's shape); null includes all.

Returns

NDArray

out itself when given; otherwise a fresh bool array, read-only when 0-d (NumPy's scalar).

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.all.html. NumSharp's static-typing rule ([PlainReceiver]): called on a numpy.matrix through an NDArray reference it computes as the plain array (the matrix's own all is all(NDAxis?, NDArray)). The axis is an NDAxis since API-parity batch 4 (2026-11-12); an int? argument converts.

Exceptions

AxisError

An axis is out of bounds.

ValueError

A tuple names an axis twice (duplicate value in 'axis'), or a read-only or misshapen out / where (NumPy's reduction texts).

IncorrectShapeException

where or out does not broadcast against this array.

TypeError

out is a C# scalar.

all(NDAxis?, NDArray, bool, NDArray)

NumPy's ndarray.all(axis=None, out=None, keepdims=False, *, where=True): whether every element evaluates to True along the given axes. Refer to all(NDArray, NDAxis?, NDArray, bool, NDArray) for the full contract.

public NDArray all(NDAxis? axis = null, NDArray @out = null, bool keepdims = false, NDArray where = null)

Parameters

axis NDAxis?

NumPy's axis: null (None, the default) reduces every axis; one axis or a tuple ((0, 2), new[] { 0, 2 }) reduces those axes; the empty tuple reduces none.

out NDArray

An array of the result's shape and any dtype to store the result in (and return); null for a fresh bool array. A C# scalar here is NumPy's TypeError (return arrays must be of ArrayType).

keepdims bool

If true, the reduced axes are left in the result as dimensions with size one.

where NDArray

A bool mask of the elements to include (it broadcasts to this array's shape); null includes all.

Returns

NDArray

out itself when given; otherwise a fresh bool array, read-only when 0-d (NumPy's scalar).

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.all.html. NumSharp's static-typing rule ([PlainReceiver]): called on a numpy.matrix through an NDArray reference it computes as the plain array (the matrix's own all is all(NDAxis?, NDArray)). The axis is an NDAxis since API-parity batch 4 (2026-11-12); an int? argument converts.

Exceptions

AxisError

An axis is out of bounds.

ValueError

A tuple names an axis twice (duplicate value in 'axis'), or a read-only or misshapen out / where (NumPy's reduction texts).

IncorrectShapeException

where or out does not broadcast against this array.

TypeError

out is a C# scalar.

any(int, NDArray, bool, NDArray)

any(NDAxis?, NDArray, bool, NDArray) with the axis as one int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so every answer, error, layout and subclass result is that overload's.

public NDArray any(int axis, NDArray @out = null, bool keepdims = false, NDArray where = null)

Parameters

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

out NDArray

An array of the result's shape and any dtype to store the result in (and return); null for a fresh bool array. A C# scalar here is NumPy's TypeError (return arrays must be of ArrayType).

keepdims bool

If true, the reduced axes are left in the result as dimensions with size one.

where NDArray

A bool mask of the elements to include (it broadcasts to this array's shape); null includes all.

Returns

NDArray

out itself when given; otherwise a fresh bool array, read-only when 0-d (NumPy's scalar).

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.any.html. NumSharp's static-typing rule ([PlainReceiver]): called on a numpy.matrix through an NDArray reference it computes as the plain array (the matrix's own any is any(NDAxis?, NDArray)). The axis is an NDAxis since API-parity batch 4 (2026-11-12); an int? argument converts.

Exceptions

AxisError

An axis is out of bounds.

ValueError

A tuple names an axis twice (duplicate value in 'axis'), or a read-only or misshapen out / where (NumPy's reduction texts).

IncorrectShapeException

where or out does not broadcast against this array.

TypeError

out is a C# scalar.

any(int[], NDArray, bool, NDArray)

any(NDAxis?, NDArray, bool, NDArray) with the axes as an int[]: the overload an int[] binds, and a bare null too (null converts to int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple (new int[0] is ()).

public NDArray any(int[] axis, NDArray @out = null, bool keepdims = false, NDArray where = null)

Parameters

axis int[]

The axes as NumPy's tuple, or null for None.

out NDArray

An array of the result's shape and any dtype to store the result in (and return); null for a fresh bool array. A C# scalar here is NumPy's TypeError (return arrays must be of ArrayType).

keepdims bool

If true, the reduced axes are left in the result as dimensions with size one.

where NDArray

A bool mask of the elements to include (it broadcasts to this array's shape); null includes all.

Returns

NDArray

out itself when given; otherwise a fresh bool array, read-only when 0-d (NumPy's scalar).

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.any.html. NumSharp's static-typing rule ([PlainReceiver]): called on a numpy.matrix through an NDArray reference it computes as the plain array (the matrix's own any is any(NDAxis?, NDArray)). The axis is an NDAxis since API-parity batch 4 (2026-11-12); an int? argument converts.

Exceptions

AxisError

An axis is out of bounds.

ValueError

A tuple names an axis twice (duplicate value in 'axis'), or a read-only or misshapen out / where (NumPy's reduction texts).

IncorrectShapeException

where or out does not broadcast against this array.

TypeError

out is a C# scalar.

any(NDAxis?, NDArray, bool, NDArray)

NumPy's ndarray.any(axis=None, out=None, keepdims=False, *, where=True): whether any element evaluates to True along the given axes. Refer to any(NDArray, NDAxis?, NDArray, bool, NDArray) for the full contract.

public NDArray any(NDAxis? axis = null, NDArray @out = null, bool keepdims = false, NDArray where = null)

Parameters

axis NDAxis?

NumPy's axis: null (None, the default) reduces every axis; one axis or a tuple ((0, 2), new[] { 0, 2 }) reduces those axes; the empty tuple reduces none.

out NDArray

An array of the result's shape and any dtype to store the result in (and return); null for a fresh bool array. A C# scalar here is NumPy's TypeError (return arrays must be of ArrayType).

keepdims bool

If true, the reduced axes are left in the result as dimensions with size one.

where NDArray

A bool mask of the elements to include (it broadcasts to this array's shape); null includes all.

Returns

NDArray

out itself when given; otherwise a fresh bool array, read-only when 0-d (NumPy's scalar).

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.any.html. NumSharp's static-typing rule ([PlainReceiver]): called on a numpy.matrix through an NDArray reference it computes as the plain array (the matrix's own any is any(NDAxis?, NDArray)). The axis is an NDAxis since API-parity batch 4 (2026-11-12); an int? argument converts.

Exceptions

AxisError

An axis is out of bounds.

ValueError

A tuple names an axis twice (duplicate value in 'axis'), or a read-only or misshapen out / where (NumPy's reduction texts).

IncorrectShapeException

where or out does not broadcast against this array.

TypeError

out is a C# scalar.

argmax()

Returns the index of the maximum value (flattened array).

public long argmax()

Returns

long

The index of the maximal value in the flattened array.

Remarks

argmax(NDAxis?, NDArray, bool)

NumPy's ndarray.argmax(axis=None, out=None, *, keepdims=False): the int64 indices of the maximum values along axis (the first occurrence), or of the C-order flattened array.

public NDArray argmax(NDAxis? axis = null, NDArray @out = null, bool keepdims = false)

Parameters

axis NDAxis?

The axis along which to operate, or null for the flattened array (ONE axis: a tuple is NumPy's TypeError).

out NDArray

If provided, the indices are written into it and it is returned (see argmax(NDArray, NDAxis?, NDArray, bool)).

keepdims bool

If true, the reduced axis is left in the result with length one.

Returns

NDArray

The int64 indices, or out.

Remarks

Exceptions

AxisError

axis is outside the array's rank.

ValueError

The reduced length is 0, or out has another shape.

TypeError

out's dtype does not cast safely to int64; axis is a tuple ('tuple' object cannot be interpreted as an integer); out is a C# scalar (output must be an array: the second positional parameter is out=, so write keepdims: by name).

argmax(int?, NDArray, bool)

argmax(NDAxis?, NDArray, bool) with the axis as an int?: the overload a C# integer, an int?, a bare null and default bind (NumPy's axis here is ONE integer, so there is no int[] form, and null / default stay None), forwarding to the NDAxis form, so every answer and error is that overload's.

public NDArray argmax(int? axis, NDArray @out = null, bool keepdims = false)

Parameters

axis int?

The axis, or null for the flattened array.

out NDArray

If provided, the indices are written into it and it is returned (see argmax(NDArray, NDAxis?, NDArray, bool)).

keepdims bool

If true, the reduced axis is left in the result with length one.

Returns

NDArray

The int64 indices, or out.

Remarks

Exceptions

AxisError

axis is outside the array's rank.

ValueError

The reduced length is 0, or out has another shape.

TypeError

out's dtype does not cast safely to int64; axis is a tuple ('tuple' object cannot be interpreted as an integer); out is a C# scalar (output must be an array: the second positional parameter is out=, so write keepdims: by name).

argmin()

Returns the index of the minimum value (flattened array).

public long argmin()

Returns

long

The index of the minimum value in the flattened array.

Remarks

argmin(NDAxis?, NDArray, bool)

NumPy's ndarray.argmin(axis=None, out=None, *, keepdims=False): the int64 indices of the minimum values along axis (the first occurrence), or of the C-order flattened array.

public NDArray argmin(NDAxis? axis = null, NDArray @out = null, bool keepdims = false)

Parameters

axis NDAxis?

The axis along which to operate, or null for the flattened array (ONE axis: a tuple is NumPy's TypeError).

out NDArray

If provided, the indices are written into it and it is returned (see argmin(NDArray, NDAxis?, NDArray, bool)).

keepdims bool

If true, the reduced axis is left in the result with length one.

Returns

NDArray

The int64 indices, or out.

Remarks

Exceptions

AxisError

axis is outside the array's rank.

ValueError

The reduced length is 0, or out has another shape.

TypeError

out's dtype does not cast safely to int64; axis is a tuple ('tuple' object cannot be interpreted as an integer); out is a C# scalar (output must be an array: the second positional parameter is out=, so write keepdims: by name).

argmin(int?, NDArray, bool)

argmin(NDAxis?, NDArray, bool) with the axis as an int?: the overload a C# integer, an int?, a bare null and default bind (NumPy's axis here is ONE integer, so there is no int[] form, and null / default stay None), forwarding to the NDAxis form, so every answer and error is that overload's.

public NDArray argmin(int? axis, NDArray @out = null, bool keepdims = false)

Parameters

axis int?

The axis, or null for the flattened array.

out NDArray

If provided, the indices are written into it and it is returned (see argmin(NDArray, NDAxis?, NDArray, bool)).

keepdims bool

If true, the reduced axis is left in the result with length one.

Returns

NDArray

The int64 indices, or out.

Remarks

Exceptions

AxisError

axis is outside the array's rank.

ValueError

The reduced length is 0, or out has another shape.

TypeError

out's dtype does not cast safely to int64; axis is a tuple ('tuple' object cannot be interpreted as an integer); out is a C# scalar (output must be an array: the second positional parameter is out=, so write keepdims: by name).

argpartition(NDArray, int?, string, string)

Returns the int64 indices that would partition this array, with the kth indices given as an ARRAY (NumPy's array-kth form — see the np.argpartition overload).

public NDArray argpartition(NDArray kth, int? axis = -1, string kind = "introselect", string order = null)

Parameters

kth NDArray
axis int?
kind string
order string

Returns

NDArray

argpartition(int, int?, string, string)

Returns the int64 indices that would partition this array along axis (NumPy ndarray.argpartition). This array is only read.

public NDArray argpartition(int kth, int? axis = -1, string kind = "introselect", string order = null)

Parameters

kth int
axis int?
kind string
order string

Returns

NDArray

argpartition(int[], int?, string, string)

Returns the int64 indices that would partition this array around every index in kth at once (NumPy ndarray.argpartition).

public NDArray argpartition(int[] kth, int? axis = -1, string kind = "introselect", string order = null)

Parameters

kth int[]
axis int?
kind string
order string

Returns

NDArray

argsort(int?, string, object, bool?, bool?)

Returns the indices that would sort this array along axis (null flattens). NumPy's ndarray.argsort(axis=-1, kind=None, order=None, *, stable=None, descending=False).

public NDArray argsort(int? axis = -1, string kind = null, object order = null, bool? stable = null, bool? descending = null)

Parameters

axis int?

Axis to sort along; null sorts the flattened array.

kind string

The sort algorithm, as NumPy parses it: the first letter decides, case-insensitively — 'q'uicksort (the default), 'h'eapsort (the default kind under another name), 'm'ergesort or 's'table. Over S / U text the default kind gives NumPy's introsort permutation (equal strings in its order, which is not their input order once a line has more than 16 elements) and the stable kinds the stable permutation; NumSharp's numeric ascending argsort gives the stable permutation for every kind, its descending default-kind argsort NumPy's introsort permutation.

order object

Field names; any value is refused (no NumSharp dtype has fields).

stable bool?

NumPy's keyword-only stable: true asks for the stable kind. It cannot be combined with kind (false included).

descending bool?

NumPy 2.5's keyword-only descending: true orders the largest value first, NaN still last. It cannot be combined with kind (false included).

Returns

NDArray

A fresh, C-contiguous int64 array of indices.

Exceptions

ValueError

An unknown kind, kind given with stable or descending, or an order.

AxisError

The axis is out of bounds (a 0-d array ravels first, so it accepts 0 and -1).

RuntimeError

A StringDType array sorted descending (unsupported sort kind), before the axis check.

ValueError

A StringDType line of two or more elements that holds an NA of a descriptor whose NA object is neither a string nor NaN-like (NumPy's Cannot compare null that is not a nan-like value, raised after the lines before it were sorted).

MemoryError

A corrupt StringDType cell (NumPy's MemoryError text).

array_equal(NDArray, bool)

True if this array and rhs have the same shape and all elements are equal: NumSharp's member for np.array_equal(this, rhs, equal_nan) (NumPy has no ndarray method of that name), with the function's answers for every dtype, text and StringDType included.

public bool array_equal(NDArray rhs, bool equal_nan = false)

Parameters

rhs NDArray

The array to compare against; null is never equal.

equal_nan bool

When false (the NumPy default) NaN never compares equal — an array holding a NaN is NOT equal even to itself, so a.array_equal(a) is false when a contains a NaN. When true, NaNs at matching positions are treated as equal, and for a complex dtype a value counts as NaN when EITHER component is NaN; a NaN-like NA of StringDType is a NaN.

Returns

bool

Returns True if the arrays are equal.

Remarks

Faithful port of NumPy 2.4.2's array_equal. Shape must match EXACTLY (no broadcasting; see array_equiv(NDArray, NDArray) for the broadcasting variant), and the shape check runs FIRST. The default path is all(this == rhs) — deliberately WITHOUT a same-reference short-circuit, because NaN ≠ NaN means an array with a NaN is not equal to itself here; a same-reference short-circuit is only valid under equal_nan. Dtypes that cannot hold NaN (bool / all integer widths / char / decimal) skip the NaN machinery: their isnan is uniformly false, so the fast path yields the identical result NumPy would (this also sidesteps calling isnan on Char/Decimal, which have no NumPy analog). Footgun: a fixed-width text operand cannot take equal_nan — NumPy's isnan refuses it unless both operands are the same object (or the shapes differ). https://numpy.org/doc/stable/reference/generated/numpy.array_equal.html

Exceptions

TypeError

With equal_nan, a fixed-width string operand and two different arrays of one shape (NumPy's isnan has no string loop); two StringDType operands whose NA objects differ (their comparison refuses the pair).

astype(DType, char, string, bool)

Copy of the array, cast to a specified type and memory layout: NumPy's a.astype(dtype, order='K', casting='unsafe', subok=True, copy=True).

[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray astype(DType dtype, char order = 'K', string casting = "unsafe", bool copy = true)

Parameters

dtype DType

The dtype to cast this array to — one descriptor parameter, like NumPy's dtype: a C# Type (typeof(float)), an NPTypeCode, a NumPy dtype string ("f4", "float32") or a DType (np.float32, other.dtype) all convert implicitly. Null is NumPy's astype(None): the default dtype, float64 (a float64 array with copy false comes back itself).

order char

Controls the memory layout: 'C' (row-major), 'F' (column-major), 'A' - 'F' if source is F-contiguous (and not C-contiguous) else 'C', 'K' (default) - preserve the source layout.

casting string

NumPy's cast-rule gate ('no' / 'equiv' / 'safe' / 'same_kind' / 'unsafe', and NumPy 2.4's 'same_value'). Default 'unsafe' (matches NumPy's astype default) — any conversion is permitted. A stricter rule raises InvalidCastException (NumPy's TypeError analogue) when the source dtype cannot cast to dtype under that rule.

copy bool

By default, astype always returns a newly allocated array. If this is set to false and the dtype (and the order) requirement is already satisfied, the input array itself is returned instead of a copy; when a conversion is needed a new array is still allocated and the input is never modified (NumPy semantics).

Returns

NDArray

An NDArray of given dtype with the requested layout.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.astype.html

    <p>One signature in NumPy's keyword order (API-parity batch 3, 2026-11-11): it replaces the former
    <code>astype(dtype, copy)</code> / <code>astype(dtype, copy, order, casting)</code> pair, so <code>a.astype(t, 'F')</code> reads as
    in NumPy and a <code>copy</code> is written <code>copy: false</code> (a bool in the order slot does not compile).
    <code>subok</code> stays out (the parity plan's exclusion).</p>

Exceptions

NotSupportedException

The descriptor's class has no storage lane yet (a datetime64/timedelta64 descriptor before Stage C), or casting is 'same_value' for a numeric cast between two storage types (NumSharp has no value-checking cast loop yet; a cast within one storage type changes no value and runs).

ValueError

An unknown order (order must be one of 'C', 'F', 'A', or 'K' (got '…')), then an unknown casting name (casting must be one of 'no', 'equiv', 'safe', 'same_kind', 'unsafe', 'same_value' (got '…')): NumPy's argument parsing, before anything else.

InvalidCastException

The cast is not allowed under casting.

byteswap(bool)

Swap the bytes of the array elements — toggle between low-endian and big-endian data representation. Mirrors NumPy's ndarray.byteswap(inplace=False): the dtype is unchanged and only the raw element bytes are reversed, so the reinterpreted values change. A complex element has its real and imaginary parts swapped individually; 1-byte dtypes are an in-place no-op (but inplace=False still returns a fresh copy).

public NDArray byteswap(bool inplace = false)

Parameters

inplace bool

When true, swap this array's data in place and return this same instance. When false (default), return a byte-swapped copy and leave this array untouched.

Returns

NDArray

The byte-swapped array (this instance when inplace, else a copy).

Remarks

A NEP 55 StringDType array has no byte order to toggle: its cells point into its buffer's allocator, and NumPy leaves the class's copyswapn NULL, which NumPy 2.5 reports as a TypeError. NumPy 2.4 crashed the process on this call, and NumSharp then answered the identity swap (a copy, or this instance in place).

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.byteswap.html

Exceptions

ValueError

When inplace is true and the array is not writeable (e.g. a broadcast view).

TypeError

A NEP 55 StringDType array, whatever its size: dtype StringDType() does not implement copyswap (raised after the in-place writeable check).

choose(NDArray, NDArray, string)

Use this index array to choose from a single choices array whose outermost dimension is the sequence. Refer to choose(NDArray, NDArray, NDArray, string) for full documentation.

public NDArray choose(NDArray choices, NDArray @out = null, string mode = "raise")

Parameters

choices NDArray
out NDArray
mode string

Returns

NDArray

choose(NDArray[], NDArray, string)

Use this index array to choose from choices (the common case — every choice is an NDArray). Refer to choose(NDArray, NDArray[], NDArray, string) for full documentation.

public NDArray choose(NDArray[] choices, NDArray @out = null, string mode = "raise")

Parameters

choices NDArray[]
out NDArray
mode string

Returns

NDArray

choose(object[], NDArray, string)

Use this index array to construct a new array from a set of choices. Refer to choose(NDArray, object[], NDArray, string) for full documentation.

public NDArray choose(object[] choices, NDArray @out = null, string mode = "raise")

Parameters

choices object[]

The choice arrays (each an NDArray or a boxed C# scalar). This array supplies the indices [0, n-1] into them.

out NDArray

Optional destination array whose shape equals the broadcast result shape.

mode string

Out-of-bounds behaviour: "raise" (default), "wrap" or "clip".

Returns

NDArray

Remarks

clip(NDArray, NDArray, NDArray, DType, NDArray)

Return an array whose values are limited to [min, max]. If neither min nor max is given the array is returned unchanged (a copy; NumPy's np.positive, which refuses a bool array). On an integer array an integer bound at or past the dtype's limit is ignored, and a kept one that does not fit raises OverflowException instead of wrapping. Refer to clip(NDArray, NDArray, NDArray, NDArray, DType, NDArray, NDArray, NDArray) for full documentation.

public NDArray clip(NDArray min = null, NDArray max = null, NDArray @out = null, DType dtype = null, NDArray where = null)

Parameters

min NDArray

Minimum value. If null, clipping is not performed on the lower interval edge. An array bound broadcasts against this array.

max NDArray

Maximum value. If null, clipping is not performed on the upper interval edge.

out NDArray

The results will be placed in this array, which is returned as-is. It may be this array for in-place clipping, or overlap it in any other way (the result is computed as if from a copy).

dtype DType

The dtype the computation runs in (NumPy's ndarray.clip(..., **kwargs) passes dtype through to the ufunc). Null (default) keeps the promoted result dtype.

where NDArray

NumPy's ufunc where= mask (bool, broadcast with the operands): only its True positions are written.

Returns

NDArray

An array with the elements of this array, but where values < min are replaced with min, and those > max with max.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.clip.html

NumPy's ndarray.clip forwards to _methods._clip(a, min=None, max=None, out=None, **kwargs) directly, so the a_min/min keyword rule of np.clip does not apply here: min and max are the only bound parameters.

Exceptions

OverflowError

A kept integer bound does not fit the integer dtype the computation runs in.

TypeError

A dtype or out that breaks NumPy's same_kind casting rule.

ArgumentException

A non-bool where.

ValueError

out is read-only, or the operands do not broadcast together / out would be stretched.

TypeError

No bound is left and the computation would run in bool.

compress(NDArray, int?, NDArray)

Return selected slices of this array along the given axis. Refer to compress(NDArray, NDArray, int?, NDArray) for full documentation.

public NDArray compress(NDArray condition, int? axis = null, NDArray @out = null)

Parameters

condition NDArray

1-D boolean array selecting which entries to return. If longer than the axis length the extra entries are treated as false.

axis int?

Axis along which to take slices. The default (null) works over the flattened array.

out NDArray

Output array whose type is preserved and which must be of the right shape to hold the output.

Returns

NDArray

A copy of the selected slices along the given axis.

Remarks

conj(NDArray)

Alias of conjugate(NDArray) — return the complex conjugate, element-wise (NumPy: ndarray.conj is ndarray.conjugate).

public NDArray conj(NDArray @out = null)

Parameters

out NDArray

Optional destination. When given it receives the result and is returned.

Returns

NDArray

Remarks

conjugate(NDArray)

Return the complex conjugate, element-wise (NumPy's ndarray.conjugate method — the port of PyArray_Conjugate, which is NOT the np.conjugate ufunc). For a COMPLEX array the imaginary sign is flipped. For a real / integer / boolean array the values are already their own conjugate, so — unlike the conjugate(NDArray, NDArray, NDArray, DType) FUNCTION, which has no bool loop and promotes bool→int8 — the method PRESERVES the dtype: with no out it returns THIS array itself (NumPy returns self), and with an out it copies the values there under NumPy's default (same_kind) assignment casting.

public NDArray conjugate(NDArray @out = null)

Parameters

out NDArray

Optional destination. When given it receives the result and is returned.

Returns

NDArray

The conjugate: a new array, out itself, or — for a non-complex array without out — this array itself (not a copy: a caller must not dispose it as its own).

Remarks

Exceptions

TypeError

A string array: "cannot conjugate non-numeric dtype" (NumPy's text).

InvalidCastException

out's dtype is not reachable under same_kind casting (np.copyto's, or the ufunc's out cast for a complex array).

ValueError

out is read-only or its shape does not take the result.

convolve(NDArray, string)

Returns the discrete, linear convolution of two one-dimensional sequences.

The convolution operator is often seen in signal processing, where it models the effect of a linear time-invariant system on a signal[1]. In probability theory, the sum of two independent random variables is distributed according to the convolution of their individual distributions.

If v is longer than a, the arrays are swapped before computation.

public NDArray convolve(NDArray v, string mode = "full")

Parameters

v NDArray

The second one-dimensional input array.

mode string

'full', 'same', or 'valid'. Default is 'full'.

Returns

NDArray

Discrete, linear convolution of a and v.

Remarks

NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.convolve.html

convolve is correlate(a, v[::-1], mode) (numpy/_core/numeric.py): NumPy's Python statements run in this array's Convolve(NDArray, NDArray, string), which reverses the kernel and calls the engine's correlation (Correlate(NDArray, NDArray, string), the shared sliding multiply-accumulate kernels). Unlike correlate it does NOT conjugate a complex kernel and is commutative, so the "swap if v longer" needs no output reversal. See np.correlate.cs for the float bit-parity notes (both share the same kernel).

Exceptions

ValueError

a cannot be empty / v cannot be empty (on the operands as given, before the length swap), then an unknown mode (NumPy's two texts, the bad argument in Python's repr), object too deep for desired array for an operand of two or more dimensions, or — for a fixed-width string operand, after every check above — function not available for this data type (NumPy's result allocation for the string type number).

UnicodeEncodeError

A mode holding a lone surrogate.

TypeError

A null mode (NumPy's None): convolve/correlate mode not understood. A StringDType operand (after the emptiness checks and the swap): NumPy's legacy-only descriptor refusal, or Python's error from the first product of the OBJECT fallback.

NotSupportedException

A StringDType operand whose OBJECT product NumPy computes (an object array, which NumSharp does not have).

copy(char)

Return a copy of the array.

public NDArray copy(char order = 'C')

Parameters

order char

Controls the memory layout of the copy. 'C' - row-major (C-style), 'F' - column-major (Fortran-style), 'A' - 'F' if this is F-contiguous (and not C-contiguous), else 'C', 'K' - match the layout of this array as closely as possible.

Returns

NDArray

A copy of the array with the requested memory layout.

Remarks

correlate(NDArray, string)

Cross-correlation of two 1-dimensional sequences: c_k = sum_n a_{n+k} * conj(v_n) (NumPy signal-processing convention).

public NDArray correlate(NDArray v, string mode = "valid")

Parameters

v NDArray

The second one-dimensional input array.

mode string

'valid', 'same', or 'full'. Default is 'valid' (unlike convolve, which defaults to 'full').

Returns

NDArray

Discrete cross-correlation of a and v.

Remarks

NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.correlate.html

Port of NumPy's PyArray_Correlate2 (numpy/_core/src/multiarray/multiarraymodule.c), the engine member Correlate2(NDArray, NDArray, string): the second argument is complex-conjugated first (real inputs unchanged); the operands are then swapped when len(a) < len(v) — correlate is NOT commutative — and the output is reversed in that case (_pyarray_revert). The kernel is read forward. Float bit-parity notes are in np.correlate.cs.

Exceptions

ValueError

First an unknown mode (NumPy's two texts, the bad argument in Python's repr); then object of too small depth for desired array (a 0-d operand) or object too deep for desired array (two or more dimensions), first array argument cannot be empty / second array argument cannot be empty, or — for a fixed-width string operand, after every check above — function not available for this data type.

UnicodeEncodeError

A mode holding a lone surrogate.

TypeError

A null mode (NumPy's None): convolve/correlate mode not understood. A StringDType operand: NumPy's legacy-only descriptor refusal (a StringDType first operand, or a U one beside it), or Python's error from the first product of the OBJECT fallback (can't multiply sequence by non-int of type 'float').

NotSupportedException

A StringDType operand whose OBJECT product NumPy computes (an object array, which NumSharp does not have).

cumprod(int?, DType, NDArray)

Return the cumulative product of the elements along a given axis.

public NDArray cumprod(int? axis = null, DType dtype = null, NDArray @out = null)

Parameters

axis int?

Axis along which the cumulative product is computed. The default (null) is to compute the cumprod over the flattened array.

dtype DType

Type of the returned array and of the accumulator in which the elements are multiplied. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used.

out NDArray

Alternate output array in which to place the result. It must have the same shape as the expected output. A reference to out is returned.

Returns

NDArray

A new array holding the result is returned unless out is specified, in which case a reference to out is returned. The result has the same size as a, and the same shape as a if axis is not None or a is a 1-d array.

Remarks

cumsum(int?, DType, NDArray)

Return the cumulative sum of the elements along a given axis.

public NDArray cumsum(int? axis = null, DType dtype = null, NDArray @out = null)

Parameters

axis int?

Axis along which the cumulative sum is computed. The default (-1) is to compute the cumsum over the flattened array.

dtype DType

Type of the returned array and of the accumulator in which the elements are summed. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used.

out NDArray

Alternate output array in which to place the result. It must have the same shape as the expected output. A reference to out is returned.

Returns

NDArray

A new array holding the result is returned unless out is specified, in which case a reference to out is returned. The result has the same size as a, and the same shape as a if axis is not None or a is a 1-d array.

Remarks

delete(IEnumerable)

Return a copy of this array with elements at indices removed. Equivalent to np.delete(this, indices, axis: null) — the array is flattened first, matching NumPy's axis=None behaviour.

public NDArray delete(IEnumerable indices)

Parameters

indices IEnumerable

Indices (any IEnumerable of integers). Negative indices are normalised; duplicates are silently collapsed.

Returns

NDArray

A new 1-D array with the selected elements removed.

Remarks

diagonal(int, int, int)

Return specified diagonals. Refer to diagonal(NDArray, int, int, int) for full documentation.

public NDArray diagonal(int offset = 0, int axis1 = 0, int axis2 = 1)

Parameters

offset int

Offset of the diagonal from the main diagonal. Can be positive or negative. Defaults to 0.

axis1 int

Axis to be used as the first axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to 0.

axis2 int

Axis to be used as the second axis of the 2-D sub-arrays from which the diagonals should be taken. Defaults to 1.

Returns

NDArray

A view onto the requested diagonal(s).

Remarks

dot(NDArray, NDArray)

Dot product of two arrays. See remarks.

public NDArray dot(NDArray b, NDArray @out = null)

Parameters

b NDArray

Rhs, Second argument.

out NDArray

NumPy's out=: the C-contiguous destination of the product, of exactly the result's shape and dtype (dot(NDArray, NDArray, NDArray)'s rules), returned itself; null allocates.

Returns

NDArray

Returns the dot product of a and b. If a and b are both scalars or both 1-D arrays then a scalar is returned; otherwise an array is returned. If out is given, then it is returned.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.dot.html
Specifically,
- If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation).
- If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred.
- If either a or b is 0-D(scalar), it is equivalent to multiply and using numpy.multiply(a, b) or a* b is preferred.
- If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.
- If a is an N-D array and b is an M-D array(where M>=2), it is a sum product over the last axis of a and the second-to-last axis of b:
dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])

Exceptions

ValueError

The shapes are not aligned, or out is not acceptable (NumPy's texts).

dstack(params NDArray[])

Stack arrays in sequence depth wise (along third axis). This is equivalent to concatenation along the third axis after 2-D arrays of shape(M, N) have been reshaped to(M, N,1) and 1-D arrays of shape(N,) have been reshaped to(1, N,1). Rebuilds arrays divided by dsplit. This function makes most sense for arrays with up to 3 dimensions.For instance, for pixel-data with a height(first axis), width(second axis), and r/g/b channels(third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations.

public NDArray dstack(params NDArray[] tup)

Parameters

tup NDArray[]

The arrays must have the same shape along all but the third axis. 1-D or 2-D arrays must have the same shape.

Returns

NDArray

The array formed by stacking the given arrays, will be at least 3-D.

Remarks

fill(object)

Fill the array with a scalar value, IN PLACE (NumPy's ndarray.fill). Every element — across whatever memory layout this array has (contiguous, F-order, sliced, transposed, negative-stride) — is set to value coerced to this array's dtype.

Coercion follows NumPy's scalar-assignment (NEP50 weak-scalar) rules, probed against NumPy 2.4.2. A C# primitive is NumSharp's analog of a Python scalar (weak): assigned to an INTEGER dtype it is range-checked — an out-of-bounds value RAISES (OverflowException "Python integer 300 out of bounds for int8") rather than wrapping, and a float source is TRUNCATED toward zero before the check (3.9 stores 3, 300.0 into int8 raises OverflowException; NaN raises ValueError "cannot convert float NaN to integer"; ±inf raises OverflowException "cannot convert float infinity to integer"; a complex source raises TypeError, exactly as NumPy's setitem runs int()/float() on the value). Assigned to a float/complex dtype it casts, saturating to ±inf on overflow (float32.fill(1e300) → inf). A 0-d NDArray is a STRONG scalar and WRAPS on cast (matching NumPy's 0-d array) — except a C# literal's own 0-d array (NumSharp.NDArray.WasPythonLiteral), which packs as the literal; a higher-rank array is a sequence and raises ValueError("setting an array element with a sequence."). A Half or char is a NumPy scalar: range-checked into a SIGNED integer dtype, cast into every other (uint8.fill((Half)300) is 44, as in NumPy). The whole conversion is NumPy's PyArray_Pack (TryPack(object, NPTypeCode, Span<byte>)), shared with every store path.

NumPy checks writeability FIRST, then packs the scalar (which may raise) BEFORE touching any element — so a read-only destination raises the read-only error even for a bad value, and an out-of-range value raises even on an EMPTY array. Both orderings are reproduced.

public void fill(object value)

Parameters

value object

The scalar to fill with. A C# primitive (weak) or a 0-d NDArray (strong); null is Python's None: NaN for a float array (NumPy's positive NPY_NAN), nan+nanj for complex, False for bool, 'None' (truncated to the width) for S / U, a StringDType's NA object or 'None'.

Remarks

Exceptions

TypeError

value is null and this is an integer (or decimal) array: Python's int(None) — raised even for an EMPTY array, as NumPy packs the scalar first.

ValueError

This array is read-only (broadcast view / read-only memmap); raises NumPy's exact ValueError: assignment destination is read-only.

OverflowError

A weak integer/float value is out of range for an integer dtype, or a ±inf value is assigned to an integer dtype (NumPy's OverflowError).

ValueError

value is a multi-element array (a sequence), or a NaN value is assigned to an integer dtype (NumPy's ValueError).

TypeError

A complex value is assigned to a real (non-bool integer or float) dtype — NumPy funnels it through int()/float(), which reject a complex.

UnicodeEncodeError

Non-ASCII text into a bytes (S) array.

UnicodeDecodeError

Non-ASCII bytes into a str (U) array.

flatten(char)

Return a copy of the array collapsed into one dimension.

public NDArray flatten(char order = 'C')

Parameters

order char

The order in which to read the elements. 'C' - row-major (C-style), 'F' - column-major (Fortran-style), 'A' - 'F' if this is F-contiguous (and not C-contiguous) else 'C', 'K' - the order the elements occur in memory: NpyIter's KEEPORDER sequence (C / F for a C- / F-contiguous array, the input's own axis order otherwise; each axis in increasing index, a broadcast axis abstaining).

Returns

NDArray

A copy of the input array, flattened to one dimension.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.flatten.html NumPy: flatten() ALWAYS returns a copy. Use ravel() for a view when possible.

Exceptions

ArgumentException

An order code other than C, F, A or K.

getfield(DType, int)

Returns a field of the array as a certain dtype — a VIEW whose elements are the offset-th byte(s) of each of this array's elements, reinterpreted as dtype. Port of NumPy's ndarray.getfield(dtype, offset=0).

public NDArray getfield(DType dtype, int offset = 0)

Parameters

dtype DType

The dtype to read the field as. Its itemsize must be ≤ this array's itemsize. Null is Python's None, which NumPy's dtype converter (PyArray_DescrConverter) reads as the default float64.

offset int

Byte offset of the field within each element. Must be in [0, itemsize − newItemsize].

Returns

NDArray

A byte-reinterpreting VIEW that SHARES memory with this array (writes through, unless this array is read-only). Its shape equals this array's shape; the byte-strides are preserved, so a narrower field of a contiguous array is a strided view.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.getfield.html

Unlike view(Type) — which rescales the last axis so the whole buffer is re-tiled into the new dtype — getfield keeps the layout and reads a sub-slice of each element's bytes. For a complex128 array, getfield(float64, 0) is the real part and getfield(float64, 8) is the imaginary part; for an int32 array, getfield(int16, 0) / getfield(int16, 2) are the low / high halves.

Exceptions

ValueError

new type is larger than original type, offset is negative, or new type plus offset is larger than original type — the verbatim NumPy texts (a null dtype, float64, is larger than any field of an array of narrower items).

TypeError

Cannot get/set field of an object array: this array or the field holds references (a StringDType, whose cells point into its allocator) and the field is not the whole element through this array's own descriptor object — an equal but separate instance is refused too (NumPy 2.5's _getfield_is_safe, checked before the size checks).

NotSupportedException

A non-native field descriptor ('>i4' on a little-endian host): NumPy reads the field byte-swapped, NumSharp stores every dtype natively and has no such view (raised after NumPy's size / offset checks, so getfield('>i8') of an int32 array is still NumPy's ValueError); an unsized string field; or a string-route field whose byte strides are not whole field items (S3 → S2: NumSharp keeps strides in elements).

getfield<T>(int)

Returns a field of the array as a certain dtype — the typed generic form of getfield(DType, int).

public NDArray<T> getfield<T>(int offset = 0) where T : unmanaged

Parameters

offset int

Byte offset of the field within each element.

Returns

NDArray<T>

The typed field view (shares memory with this array; keeps its buffer alive while it lives).

Type Parameters

T

The field dtype (its itemsize must be ≤ this array's itemsize).

Remarks

Built as the typed array directly: wrapping an untyped NDArray first and calling AsGeneric made a SECOND NDArray over the alias, leaving the first — a counted reference on this array's buffer — to the finalizer, and dropping the engine the first one carried.

Exceptions

ValueError

One of getfield(DType, int)'s dtype / offset texts.

TypeError

Cannot get/set field of an object array: this array is a StringDType array (its cells hold references; a numeric field of them is never the whole element in its own descriptor).

hstack(params NDArray[])

Stack arrays in sequence horizontally (column wise). This is equivalent to concatenation along the second axis, except for 1-D arrays where it concatenates along the first axis.Rebuilds arrays divided by hsplit. This function makes most sense for arrays with up to 3 dimensions.For instance, for pixel-data with a height(first axis), width(second axis), and r/g/b channels(third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations.

public NDArray hstack(params NDArray[] tup)

Parameters

tup NDArray[]

The arrays must have the same shape along all but the second axis, except 1-D arrays which can be any length.

Returns

NDArray

The array formed by stacking the given arrays.

Remarks

item()

Copy an element of an array to a standard Python scalar and return it.

public object item()

Returns

object

A copy of the specified element of the array as a suitable Python scalar.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.item.html

When called without arguments, works only for arrays with one element (size 1), which can have any shape (0-d, 1-element 1-d, 1x1 2-d, etc.).

This is the NumPy 2.x replacement for the deprecated np.asscalar().

Exceptions

ValueError

The array does not hold exactly one element (NumPy's can only convert an array of size 1 to a Python scalar; an IncorrectSizeException until API-parity batch 13, parity QA-04).

item(long)

Copy an element of an array to a standard Python scalar and return it.

public object item(long index)

Parameters

index long

Flat index of element to extract (supports negative indexing).

Returns

object

A copy of the specified element of the array as a suitable Python scalar.

Remarks

item(long, long)

Copy an element of an array to a standard Python scalar and return it.

public object item(long i, long j)

Parameters

i long

Index along first dimension.

j long

Index along second dimension.

Returns

object

A copy of the specified element of the array as a suitable Python scalar.

Remarks

Exceptions

ValueError

The array is not 2-D (NumPy's incorrect number of indices for array).

IndexOutOfRangeException

An index outside its axis.

item(long, long, long)

Copy an element of an array to a standard Python scalar and return it.

public object item(long i, long j, long k)

Parameters

i long

Index along first dimension.

j long

Index along second dimension.

k long

Index along third dimension.

Returns

object

A copy of the specified element of the array as a suitable Python scalar.

Remarks

Exceptions

ValueError

The array is not 3-D (NumPy's incorrect number of indices for array).

IndexOutOfRangeException

An index outside its axis.

item(params long[])

Copy an element of an array to a standard Python scalar and return it.

public object item(params long[] indices)

Parameters

indices long[]

Indices of element to extract (one per dimension).

Returns

object

A copy of the specified element of the array as a suitable Python scalar.

Remarks

Exceptions

ValueError

Not one index per dimension (NumPy's incorrect number of indices for array).

IndexOutOfRangeException

An index outside its axis.

item<T>()

Copy an element of an array to a standard Python scalar and return it.

public T item<T>() where T : unmanaged

Returns

T

A copy of the specified element of the array as a typed scalar.

Type Parameters

T

The type to convert the value to.

Exceptions

ValueError

The array does not hold exactly one element (NumPy's can only convert an array of size 1 to a Python scalar).

item<T>(long)

Copy an element of an array to a standard Python scalar and return it.

public T item<T>(long index) where T : unmanaged

Parameters

index long

Flat index of element to extract (supports negative indexing).

Returns

T

A copy of the specified element of the array as a typed scalar.

Type Parameters

T

The type to convert the value to.

item<T>(long, long)

Copy an element of an array to a standard Python scalar and return it.

public T item<T>(long i, long j) where T : unmanaged

Parameters

i long

Index along first dimension.

j long

Index along second dimension.

Returns

T

A copy of the specified element of the array as a typed scalar.

Type Parameters

T

The type to convert the value to.

Exceptions

ValueError

The array is not 2-D (incorrect number of indices for array).

IndexOutOfRangeException

An index outside its axis.

item<T>(long, long, long)

Copy an element of an array to a standard Python scalar and return it.

public T item<T>(long i, long j, long k) where T : unmanaged

Parameters

i long

Index along first dimension.

j long

Index along second dimension.

k long

Index along third dimension.

Returns

T

A copy of the specified element of the array as a typed scalar.

Type Parameters

T

The type to convert the value to.

Exceptions

ValueError

The array is not 3-D (incorrect number of indices for array).

IndexOutOfRangeException

An index outside its axis.

item<T>(params long[])

Copy an element of an array to a standard Python scalar and return it.

public T item<T>(params long[] indices) where T : unmanaged

Parameters

indices long[]

Indices of element to extract (one per dimension).

Returns

T

A copy of the specified element of the array as a typed scalar.

Type Parameters

T

The type to convert the value to.

Exceptions

ValueError

Not one index per dimension (incorrect number of indices for array).

IndexOutOfRangeException

An index outside its axis.

itemset(Shape, object)

Stores one boxed element at the coordinates shape's dimensions name — NumPy 1.x's ndarray.itemset (removed in NumPy 2.0, whose spelling is a[i, j] = value).

public void itemset(Shape shape, object val)

Parameters

shape Shape

A shape whose DIMENSIONS are read as the element's coordinates (a legacy spelling).

val object

The element, boxed as the dtype's exact CLR type (an unboxing, never a conversion), or null for Python's None.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

InvalidCastException

A non-null value that is not the dtype's exact CLR type.

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing is written).

itemset(ref Shape, object)

Stores one boxed element at the coordinates shape's dimensions name — NumPy 1.x's ndarray.itemset (removed in NumPy 2.0, whose spelling is a[i, j] = value).

public void itemset(ref Shape shape, object val)

Parameters

shape Shape

A shape whose DIMENSIONS are read as the element's coordinates (a legacy spelling).

val object

The element, boxed as the dtype's exact CLR type (an unboxing, never a conversion), or null for Python's None.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

InvalidCastException

A non-null value that is not the dtype's exact CLR type.

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing is written).

itemset(int[], object)

Stores one boxed element at the coordinates shape — NumPy 1.x's ndarray.itemset (removed in NumPy 2.0, whose spelling is a[i, j] = value).

public void itemset(int[] shape, object val)

Parameters

shape int[]

The element's coordinates; a negative coordinate counts from the end of its axis.

val object

The element, boxed as the dtype's exact CLR type (an unboxing, never a conversion), or null for Python's None.

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

InvalidCastException

A non-null value that is not the dtype's exact CLR type.

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing is written).

itemset<T>(int[], T)

Stores val at the coordinates shape, cast to the array's dtype with NumPy's cast when T is another type — NumPy 1.x's ndarray.itemset (removed in NumPy 2.0, whose spelling is a[i, j] = value).

public void itemset<T>(int[] shape, T val) where T : unmanaged

Parameters

shape int[]

The element's coordinates; a negative coordinate counts from the end of its axis.

val T

The value to store.

Type Parameters

T

The value's type.

Remarks

Before parity QA-12 a T other than the dtype wrote sizeof(T) raw bytes (the generic setter now converts).

Exceptions

ValueError

The array is read-only (assignment destination is read-only).

IndexError

A coordinate outside its axis, or more coordinates than dimensions (NumPy's texts; nothing is written).

matrix_power(int)

Raises this square matrix to the (integer) power power.

public NDArray matrix_power(int power)

Parameters

power int

Returns

NDArray

Remarks

The method form of matrix_power(NDArray, int); see it for the full contract.

This used to reject a NEGATIVE power outright ("matrix_power just work with int >= 0"), which was never NumPy's rule — a**-n is inv(a)**n. It now takes that route, so a negative power computes wherever a matrix backend is installed and raises OpenBlasMissingBackendException where none is. Three other behaviours came with the delegation: a non-square operand now raises LinAlgError rather than failing inside the product, power == 0 returns the identity in THIS array's dtype instead of always float64, and the chain is evaluated by binary exponentiation rather than one multiply per step.

max(int, NDArray, bool, object, NDArray)

max(NDAxis?, NDArray, bool, object, NDArray) with the axis as one int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so every answer, error, layout and subclass result is that overload's.

public NDArray max(int axis, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)

Parameters

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

out NDArray

The array the result is written into and returned (any dtype; a narrowing one is lossy, as in NumPy — see max(NDArray, NDAxis?, NDArray, bool, object, NDArray)). Footgun: the second positional parameter, as in NumPy, so a.max(1, true) passes the bool as out and raises; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions (keyword-only in NumPy).

initial object

The value every output starts from, or null; required with where (keyword-only in NumPy).

where NDArray

A bool mask of the elements to reduce, or null (keyword-only in NumPy).

Returns

NDArray

out itself when given; else a fresh array (0-d for a flat reduction without keepdims).

Remarks

The member keeps the plain-array meaning for a numpy.matrix object (an NDMatrix declares its own max). https://numpy.org/doc/stable/reference/generated/numpy.ndarray.max.html

Exceptions

TypeError

out is a C# scalar converted to a 0-d array (as in a.max(1, true)): NumPy's "return arrays must be of ArrayType"; also initial is complex for a real loop or of an unconvertible type.

ValueError

A read-only or misshapen out, where without initial, an empty reduced axis without initial, or an unconvertible initial. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does not fit an integer loop.

max(int[], NDArray, bool, object, NDArray)

max(NDAxis?, NDArray, bool, object, NDArray) with the axes as an int[]: the overload an int[] binds, and a bare null too (null converts to int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple (new int[0] is ()).

public NDArray max(int[] axis, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)

Parameters

axis int[]

The axes as NumPy's tuple, or null for None.

out NDArray

The array the result is written into and returned (any dtype; a narrowing one is lossy, as in NumPy — see max(NDArray, NDAxis?, NDArray, bool, object, NDArray)). Footgun: the second positional parameter, as in NumPy, so a.max(1, true) passes the bool as out and raises; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions (keyword-only in NumPy).

initial object

The value every output starts from, or null; required with where (keyword-only in NumPy).

where NDArray

A bool mask of the elements to reduce, or null (keyword-only in NumPy).

Returns

NDArray

out itself when given; else a fresh array (0-d for a flat reduction without keepdims).

Remarks

The member keeps the plain-array meaning for a numpy.matrix object (an NDMatrix declares its own max). https://numpy.org/doc/stable/reference/generated/numpy.ndarray.max.html

Exceptions

TypeError

out is a C# scalar converted to a 0-d array (as in a.max(1, true)): NumPy's "return arrays must be of ArrayType"; also initial is complex for a real loop or of an unconvertible type.

ValueError

A read-only or misshapen out, where without initial, an empty reduced axis without initial, or an unconvertible initial. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does not fit an integer loop.

max(NDAxis?, NDArray, bool, object, NDArray)

Return the maximum along an axis — NumPy's ndarray.max(axis=None, out=None, *, keepdims=<no value>, initial=<no value>, where=<no value>), i.e. max(NDArray, NDAxis?, NDArray, bool, object, NDArray) on this array. This is the only overload.

public NDArray max(NDAxis? axis = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)

Parameters

axis NDAxis?

The axis to reduce (negative counts from the end), or null for every axis. A tuple ((0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).

out NDArray

The array the result is written into and returned (any dtype; a narrowing one is lossy, as in NumPy — see max(NDArray, NDAxis?, NDArray, bool, object, NDArray)). Footgun: the second positional parameter, as in NumPy, so a.max(1, true) passes the bool as out and raises; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions (keyword-only in NumPy).

initial object

The value every output starts from, or null; required with where (keyword-only in NumPy).

where NDArray

A bool mask of the elements to reduce, or null (keyword-only in NumPy).

Returns

NDArray

out itself when given; else a fresh array (0-d for a flat reduction without keepdims).

Remarks

The member keeps the plain-array meaning for a numpy.matrix object (an NDMatrix declares its own max). https://numpy.org/doc/stable/reference/generated/numpy.ndarray.max.html

Exceptions

TypeError

out is a C# scalar converted to a 0-d array (as in a.max(1, true)): NumPy's "return arrays must be of ArrayType"; also initial is complex for a real loop or of an unconvertible type.

ValueError

A read-only or misshapen out, where without initial, an empty reduced axis without initial, or an unconvertible initial. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does not fit an integer loop.

mean(int, DType, NDArray, bool, NDArray)

mean(NDAxis?, DType, NDArray, bool, NDArray) with the axis as one int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so every answer, error, layout and subclass result is that overload's.

public NDArray mean(int axis, DType dtype = null, NDArray @out = null, bool keepdims = false, NDArray where = null)

Parameters

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

dtype DType

The dtype the sum is computed in and the mean returned in, or null for NumPy's default (float64 for bool / integer input, float32 summing a float16 input into a float16 result).

out NDArray

The array the mean is written into and returned (the sum is stored into it and divided in place, with unsafe casts). Footgun: the THIRD positional parameter, as in NumPy, so write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions.

where NDArray

A bool mask of the elements each output averages, or null.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a mean over every axis without keepdims.

Remarks

The member keeps the plain-array meaning for a numpy.matrix object reached through an NDArray reference.

Exceptions

AxisError

axis is out of bounds.

ValueError

A read-only or misshapen out. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

IncorrectShapeException

out or where does not broadcast.

TypeError

A C# scalar passed as out; NumPy's text refusals.

mean(int[], DType, NDArray, bool, NDArray)

mean(NDAxis?, DType, NDArray, bool, NDArray) with the axes as an int[]: the overload an int[] binds, and a bare null too (null converts to int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple (new int[0] is ()).

public NDArray mean(int[] axis, DType dtype = null, NDArray @out = null, bool keepdims = false, NDArray where = null)

Parameters

axis int[]

The axes as NumPy's tuple, or null for None.

dtype DType

The dtype the sum is computed in and the mean returned in, or null for NumPy's default (float64 for bool / integer input, float32 summing a float16 input into a float16 result).

out NDArray

The array the mean is written into and returned (the sum is stored into it and divided in place, with unsafe casts). Footgun: the THIRD positional parameter, as in NumPy, so write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions.

where NDArray

A bool mask of the elements each output averages, or null.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a mean over every axis without keepdims.

Remarks

The member keeps the plain-array meaning for a numpy.matrix object reached through an NDArray reference.

Exceptions

AxisError

axis is out of bounds.

ValueError

A read-only or misshapen out. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

IncorrectShapeException

out or where does not broadcast.

TypeError

A C# scalar passed as out; NumPy's text refusals.

mean(NDAxis?, DType, NDArray, bool, NDArray)

NumPy's ndarray.mean(axis=None, dtype=None, out=None, *, keepdims=<no value>, where=<no value>) (_methods._mean): the arithmetic mean over axis. This is the only overload: NumPy's whole signature (np-layer dtype plan P10, D10); the parameters behave as mean(NDArray, NDAxis?, DType, NDArray, bool, NDArray)'s.

public NDArray mean(NDAxis? axis = null, DType dtype = null, NDArray @out = null, bool keepdims = false, NDArray where = null)

Parameters

axis NDAxis?

The axis to average over (negative counts from the end); null averages every element. A tuple ((0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).

dtype DType

The dtype the sum is computed in and the mean returned in, or null for NumPy's default (float64 for bool / integer input, float32 summing a float16 input into a float16 result).

out NDArray

The array the mean is written into and returned (the sum is stored into it and divided in place, with unsafe casts). Footgun: the THIRD positional parameter, as in NumPy, so write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions.

where NDArray

A bool mask of the elements each output averages, or null.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a mean over every axis without keepdims.

Remarks

The member keeps the plain-array meaning for a numpy.matrix object reached through an NDArray reference.

Exceptions

AxisError

axis is out of bounds.

ValueError

A read-only or misshapen out. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

IncorrectShapeException

out or where does not broadcast.

TypeError

A C# scalar passed as out; NumPy's text refusals.

min(int, NDArray, bool, object, NDArray)

min(NDAxis?, NDArray, bool, object, NDArray) with the axis as one int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so every answer, error, layout and subclass result is that overload's.

public NDArray min(int axis, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)

Parameters

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

out NDArray

The array the result is written into and returned. Footgun: the second positional parameter, as in NumPy, so a.min(1, true) passes the bool as out and raises; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions (keyword-only in NumPy).

initial object

The value every output starts from, or null; required with where (keyword-only in NumPy).

where NDArray

A bool mask of the elements to reduce, or null (keyword-only in NumPy).

Returns

NDArray

out itself when given; else a fresh array (0-d for a flat reduction without keepdims).

Remarks

The member keeps the plain-array meaning for a numpy.matrix object (an NDMatrix declares its own min). https://numpy.org/doc/stable/reference/generated/numpy.ndarray.min.html

Exceptions

TypeError

out is a C# scalar converted to a 0-d array (as in a.min(1, true)): NumPy's "return arrays must be of ArrayType"; also initial is complex for a real loop or of an unconvertible type.

ValueError

A read-only or misshapen out, where without initial, an empty reduced axis without initial, or an unconvertible initial. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does not fit an integer loop.

min(int[], NDArray, bool, object, NDArray)

min(NDAxis?, NDArray, bool, object, NDArray) with the axes as an int[]: the overload an int[] binds, and a bare null too (null converts to int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple (new int[0] is ()).

public NDArray min(int[] axis, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)

Parameters

axis int[]

The axes as NumPy's tuple, or null for None.

out NDArray

The array the result is written into and returned. Footgun: the second positional parameter, as in NumPy, so a.min(1, true) passes the bool as out and raises; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions (keyword-only in NumPy).

initial object

The value every output starts from, or null; required with where (keyword-only in NumPy).

where NDArray

A bool mask of the elements to reduce, or null (keyword-only in NumPy).

Returns

NDArray

out itself when given; else a fresh array (0-d for a flat reduction without keepdims).

Remarks

The member keeps the plain-array meaning for a numpy.matrix object (an NDMatrix declares its own min). https://numpy.org/doc/stable/reference/generated/numpy.ndarray.min.html

Exceptions

TypeError

out is a C# scalar converted to a 0-d array (as in a.min(1, true)): NumPy's "return arrays must be of ArrayType"; also initial is complex for a real loop or of an unconvertible type.

ValueError

A read-only or misshapen out, where without initial, an empty reduced axis without initial, or an unconvertible initial. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does not fit an integer loop.

min(NDAxis?, NDArray, bool, object, NDArray)

Return the minimum along an axis — NumPy's ndarray.min(axis=None, out=None, *, keepdims=<no value>, initial=<no value>, where=<no value>), i.e. min(NDArray, NDAxis?, NDArray, bool, object, NDArray) on this array. This is the only overload.

public NDArray min(NDAxis? axis = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)

Parameters

axis NDAxis?

The axis to reduce (negative counts from the end), or null for every axis. A tuple ((0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).

out NDArray

The array the result is written into and returned. Footgun: the second positional parameter, as in NumPy, so a.min(1, true) passes the bool as out and raises; write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions (keyword-only in NumPy).

initial object

The value every output starts from, or null; required with where (keyword-only in NumPy).

where NDArray

A bool mask of the elements to reduce, or null (keyword-only in NumPy).

Returns

NDArray

out itself when given; else a fresh array (0-d for a flat reduction without keepdims).

Remarks

The member keeps the plain-array meaning for a numpy.matrix object (an NDMatrix declares its own min). https://numpy.org/doc/stable/reference/generated/numpy.ndarray.min.html

Exceptions

TypeError

out is a C# scalar converted to a 0-d array (as in a.min(1, true)): NumPy's "return arrays must be of ArrayType"; also initial is complex for a real loop or of an unconvertible type.

ValueError

A read-only or misshapen out, where without initial, an empty reduced axis without initial, or an unconvertible initial. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

where or out does not broadcast.

OverflowError

initial does not fit an integer loop.

negate()

Negates all values by performing: -x

public NDArray negate()

Returns

NDArray

negative()

Numerical negative, element-wise: NumPy's np.negative(x) (the -x operator), a fresh array of every element negated in the input's dtype. Unsigned integers wrap (-1 of uint8 is 255), as NumPy's loops do.

public NDArray negative()

Returns

NDArray

A fresh array of the input's dtype and shape, laid out as NumPy's ufunc allocates it (an F-ordered input gives an F-ordered result).

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.negative.html — the whole call is the engine's Negate(NDArray, DType, NDArray, NDArray), as for np.negative and the unary - operator. Until the np-layer dtype plan's P1c this member negated a C-ordered copy with its own per-dtype loop, which threw NotSupportedException for the unsigned integers and char where NumPy wraps.

Exceptions

TypeError

A bool array (NumPy's "The numpy boolean negative, the - operator, is not supported, ..." text), or text: negative has no string loop (NumPy's class-named UFuncTypeError).

nonzero()

Return the indices of the elements that are non-zero. Refer to nonzero(NDArray) for full documentation.

public NDArray<long>[] nonzero()

Returns

NDArray<long>[]

One index array per dimension, together selecting the non-zero elements in C (row-major) order.

Remarks

partition(NDArray, int?, string, string)

Partition this array in place with the kth indices given as an ARRAY (NumPy's array-kth form — see partition(NDArray, NDArray, int?, string, string) for its dtype/too-deep rejections and wrap semantics).

public void partition(NDArray kth, int? axis = -1, string kind = "introselect", string order = null)

Parameters

kth NDArray
axis int?
kind string
order string

partition(int, int?, string, string)

Partition this array in place along axis so the element at kth lands in its final sorted position (NumPy ndarray.partition; null axis flattens in place — the same NumSharp extension ndarray.sort carries).

public void partition(int kth, int? axis = -1, string kind = "introselect", string order = null)

Parameters

kth int
axis int?
kind string
order string

partition(int[], int?, string, string)

Partition this array in place around every index in kth at once (NumPy ndarray.partition with a kth sequence).

public void partition(int[] kth, int? axis = -1, string kind = "introselect", string order = null)

Parameters

kth int[]
axis int?
kind string
order string

positive()

Numerical positive, element-wise: NumPy's np.positive(x) (the unary +x operator), a fresh copy of every element in the input's dtype.

public NDArray positive()

Returns

NDArray

A fresh array of the input's dtype and shape (never the input itself), laid out as NumPy's ufunc allocates it (an F-ordered input gives an F-ordered result, a broadcast one a C-ordered result).

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.positive.html — the whole call is the engine's Positive(NDArray, DType, NDArray, NDArray), as for np.positive and the unary + operator (the np-layer dtype plan, P1c; the member checked bool and text itself and returned a Clone).

Exceptions

TypeError

A bool array: positive has identity loops for every numeric dtype EXCEPT bool (NumPy's ufunc 'positive' did not contain a loop with signature matching types <class 'numpy.dtypes.BoolDType'> -> None); or text, which has no string loop either (the class-named text).

prod(int, DType, NDArray, bool, object, NDArray)

prod(NDAxis?, DType, NDArray, bool, object, NDArray) with the axis as one int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so every answer, error, layout and subclass result is that overload's.

public NDArray prod(int axis, DType dtype = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)

Parameters

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

dtype DType

The accumulator and result dtype, or null for NumPy's default.

out NDArray

The array the product is written into and returned. Footgun: the THIRD positional parameter, as in NumPy, so write keepdims: true by name (a positional bool there is a C# scalar passed as out and raises).

keepdims bool

Keep the reduced axes as length-1 dimensions.

initial object

The value every product starts from instead of 1, or null.

where NDArray

A bool mask of the elements to multiply, or null.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a product over every axis without keepdims.

Remarks

The member keeps the plain-array meaning for a numpy.matrix object reached through an NDArray reference.

Exceptions

TypeError

A C# scalar passed as out; an initial the loop cannot take; text (NumPy's refusal).

ValueError

A read-only or misshapen out; a mask with more axes; an unconvertible initial. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

out or where does not broadcast.

OverflowError

initial does not fit an integer loop.

prod(int[], DType, NDArray, bool, object, NDArray)

prod(NDAxis?, DType, NDArray, bool, object, NDArray) with the axes as an int[]: the overload an int[] binds, and a bare null too (null converts to int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple (new int[0] is ()).

public NDArray prod(int[] axis, DType dtype = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)

Parameters

axis int[]

The axes as NumPy's tuple, or null for None.

dtype DType

The accumulator and result dtype, or null for NumPy's default.

out NDArray

The array the product is written into and returned. Footgun: the THIRD positional parameter, as in NumPy, so write keepdims: true by name (a positional bool there is a C# scalar passed as out and raises).

keepdims bool

Keep the reduced axes as length-1 dimensions.

initial object

The value every product starts from instead of 1, or null.

where NDArray

A bool mask of the elements to multiply, or null.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a product over every axis without keepdims.

Remarks

The member keeps the plain-array meaning for a numpy.matrix object reached through an NDArray reference.

Exceptions

TypeError

A C# scalar passed as out; an initial the loop cannot take; text (NumPy's refusal).

ValueError

A read-only or misshapen out; a mask with more axes; an unconvertible initial. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

out or where does not broadcast.

OverflowError

initial does not fit an integer loop.

prod(NDAxis?, DType, NDArray, bool, object, NDArray)

NumPy's ndarray.prod(axis=None, dtype=None, out=None, *, keepdims=<no value>, initial=<no value>, where=<no value>) (_methods._prod, i.e. np.multiply.reduce): the product of the elements over axis. This is the only overload: NumPy's whole signature (np-layer dtype plan P10, D10); the parameters behave as prod(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray)'s.

public NDArray prod(NDAxis? axis = null, DType dtype = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)

Parameters

axis NDAxis?

The axis to multiply over (negative counts from the end); null multiplies every element. A tuple ((0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).

dtype DType

The accumulator and result dtype, or null for NumPy's default.

out NDArray

The array the product is written into and returned. Footgun: the THIRD positional parameter, as in NumPy, so write keepdims: true by name (a positional bool there is a C# scalar passed as out and raises).

keepdims bool

Keep the reduced axes as length-1 dimensions.

initial object

The value every product starts from instead of 1, or null.

where NDArray

A bool mask of the elements to multiply, or null.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a product over every axis without keepdims.

Remarks

The member keeps the plain-array meaning for a numpy.matrix object reached through an NDArray reference.

Exceptions

TypeError

A C# scalar passed as out; an initial the loop cannot take; text (NumPy's refusal).

ValueError

A read-only or misshapen out; a mask with more axes; an unconvertible initial. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

out or where does not broadcast.

OverflowError

initial does not fit an integer loop.

put(NDArray, NDArray, string)

Set this.flat[n] = values[n] for all n in indices — an in-place operation (returns nothing). Refer to put(NDArray, NDArray, NDArray, string) for full documentation.

public void put(NDArray indices, NDArray values, string mode = "raise")

Parameters

indices NDArray

Target indices into the flattened array. Scalars are accepted via implicit conversion.

values NDArray

Values to place at indices. Broadcast/repeated to match the number of indices if necessary.

mode string

How out-of-bounds indices behave: "raise" (default), "wrap", or "clip".

Remarks

ravel(char)

Return a contiguous flattened array. A 1-D array, containing the elements of the input, is returned

public NDArray ravel(char order = 'C')

Parameters

order char

The order in which to read the elements. 'C' - row-major, 'F' - column-major, 'A' - 'F' if F-contiguous (and not C-contiguous) else 'C', 'K' - memory order.

Returns

NDArray

The 1-D result: a view that shares this array's memory (and its writeability) when the reading order walks it front to back, otherwise a fresh copy (see ravel(NDArray, char)).

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.ravel.html

    <p>One signature, NumPy's <code>a.ravel(order='C')</code>: the no-argument overload went with API-parity batch 3
    (2026-11-11), so <code>a.ravel()</code> binds here with the default 'C'.</p>

repeat(NDArray, int?)

Repeat each element of the array by the per-element counts in repeats. Refer to repeat(NDArray, NDArray, int?) for full documentation.

public NDArray repeat(NDArray repeats, int? axis = null)

Parameters

repeats NDArray

Per-element repetition counts, broadcast to the shape along the given axis.

axis int?

The axis along which to repeat values. The default (null) flattens the input array and returns a flat output array.

Returns

NDArray

Output array which has the same shape as this array, except along the given axis.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.repeat.html

    <p>One signature, NumPy's <code>a.repeat(repeats, axis=None)</code>: the <code>int</code> / <code>long</code> overloads
    went with API-parity batch 3 (2026-11-11); <code>a.repeat(3)</code> binds here (3 converts to a 0-d array).</p>

Exceptions

ValueError

A negative entry of a per-element count array (repeats may not contain negative values.).

TypeError

Counts that do not cast 'safely' to int64.

AxisError

axis is out of range.

reshape(Shape, char, bool?)

Gives a new shape to an array without changing its data, reading the elements in the specified index order — NumPy's a.reshape(shape, /, *, order='C', copy=None).

public NDArray reshape(Shape shape, char order = 'C', bool? copy = null)

Parameters

shape Shape

The new shape (one dimension may be -1 — inferred, any order): an int, a tuple, an int[] / long[], a C# collection expression (a.reshape([3, 2], order: 'F')) or a Shape; only its dimensions are read. NumPy's name (it was newShape until API-parity batch 9).

order char

Read/write index order for the reshape. 'C' (default) - row-major, 'F' - column-major, 'A' - 'F' when the source is F-contiguous and NOT C-contiguous, else 'C'; 'K' raises NumPy's ValueError("order 'K' is not permitted for reshaping").

copy bool?

NumPy's copy keyword: null (the default) copies only when the reshape cannot be a view; true ALWAYS copies (even for the same shape) — a copy in order that shares no memory with this array; false NEVER copies and raises when a view is impossible.

Returns

NDArray

A VIEW whenever the reshape can be expressed over the existing strides (contiguous-in-order relabel, or NumPy's _attempt_nocopy_reshape grouping — which can yield a non-contiguous strided view); otherwise a view over an INTERNAL copy taken in order (so the result reports owndata=False either way, exactly like NumPy's reshape).

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.reshape.html — the method form of reshape(NDArray, Shape, char, bool?) (NumPy's np.reshape calls this method). The copy keyword arrived in API-parity batch 7, with np.reshape's. Since API-parity batch 9 this and NumPy's loose ints (reshape(params long[]), reshape(params ReadOnlySpan<long>)) are the method's only spellings: the (Shape), (ref Shape) and (int[]) forms went (an int[] converts to Shape, and a.reshape([3, 2]), which the int[] form made ambiguous with the span form, binds the span form).

Exceptions

ValueError

order 'K' is not permitted for reshaping; more than one -1; Unable to avoid creating a copy while reshaping. when copy is false and no view can express the reshape (a transposed array to 1-D in C order).

IncorrectShapeException

The size does not match, with NumPy's text (cannot reshape array of size 6 into shape (4,2); NumPy's ValueError), whatever copy says.

ArgumentException

An order letter outside NumPy's vocabulary (OrderResolver's text).

reshape(params long[])

Gives a new shape to an array without changing its data — NumPy's loose integers (a.reshape(2, 3)) when the dimensions arrive as a C# long[] (an array variable, or the expanded form of compilers before C# 13).

[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray reshape(params long[] shape)

Parameters

shape long[]

The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

Returns

NDArray

This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.

Remarks

Exceptions

IncorrectShapeException

The size does not match: NumPy's cannot reshape array of size {n} into shape {s}.

ValueError

More than one dimension is negative.

reshape(params ReadOnlySpan<long>)

Gives a new shape to an array without changing its data. This is the overload inline values bind (a.reshape(2, 3), a.reshape(-1)): the values arrive on the caller's stack, so the call allocates only the dimension array the new shape keeps, as it did before the array form started to copy.

[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray reshape(params ReadOnlySpan<long> shape)

Parameters

shape ReadOnlySpan<long>

The new dimensions. One of them may be negative (the unknown dimension, inferred from the size); empty reshapes a one-element array to 0-d.

Returns

NDArray

A view whenever the reshape can be expressed over the existing strides, otherwise a view over an internal copy (NumPy's reshape; see reshape(Shape, char, bool?)).

Remarks

An array argument binds reshape(params long[]) instead (an identity conversion beats the conversion to a span), which copies it. https://numpy.org/doc/stable/reference/generated/numpy.reshape.html

Exceptions

IncorrectShapeException

The size does not match: NumPy's cannot reshape array of size {n} into shape {s}.

ValueError

More than one dimension is negative.

reshape_unsafe(Shape)

Gives a new shape to an array without changing its data.

public NDArray reshape_unsafe(Shape newshape)

Parameters

newshape Shape

The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

Returns

NDArray

This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.

Remarks

reshape_unsafe(ref Shape)

Gives a new shape to an array without changing its data.

public NDArray reshape_unsafe(ref Shape newshape)

Parameters

newshape Shape

The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

Returns

NDArray

This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.

Remarks

reshape_unsafe(int[])

Gives a new shape to an array without changing its data.

[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray reshape_unsafe(int[] shape)

Parameters

shape int[]

The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

Returns

NDArray

This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.

Remarks

reshape_unsafe(params long[])

Gives a new shape to an array without changing its data.

[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray reshape_unsafe(params long[] shape)

Parameters

shape long[]

The new shape should be compatible with the original shape. If an integer, then the result will be a 1-D array of that length. One shape dimension can be -1. In this case, the value is inferred from the length of the array and remaining dimensions.

Returns

NDArray

This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.

Remarks

reshape_unsafe(params ReadOnlySpan<long>)

Gives a new shape to an array without changing its data and without the size check of reshape(params long[]). This is the overload inline values bind (a.reshape_unsafe(2, 3)): the call allocates only the dimension array the new shape keeps.

[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray reshape_unsafe(params ReadOnlySpan<long> shape)

Parameters

shape ReadOnlySpan<long>

The new dimensions; one may be negative (inferred from the size).

Returns

NDArray

An alias of this array's storage with the new shape (a copy first when this array is not contiguous).

Remarks

Unsafe because the element count is not validated against the buffer: a shape larger than the buffer reads past it. An array argument binds reshape_unsafe(params long[]) instead, which copies it.

resize(Shape, bool)

Change shape and size of this array in-place.

Primary overload — see resize(params long[]) for the fill/truncate semantics.

public void resize(Shape new_shape, bool refcheck = true)

Parameters

new_shape Shape

Shape of resized array. A 0-d shape resizes to a scalar.

refcheck bool

If true (default), reference counting is used to check that this array's buffer is not shared with another array before resizing (when the total size changes). Set to false to skip that check.

Remarks

Exceptions

IncorrectShapeException

If this array is not single-segment (contiguous); if growing/shrinking an array that does not own its data or (with refcheck) is referenced by another array; or if a dimension is negative.

resize(params long[])

Change shape and size of this array in-place.

If the new array is larger than the original array, the new array is filled with zeros (note: this differs from resize(NDArray, Shape) which fills with repeated copies). If smaller, the data is truncated (in C-order for C-contiguous arrays, memory-order for F-contiguous ones).

Multi-argument form: a.resize(2, 3). A no-argument call a.resize() is a no-op (matches NumPy's a.resize() / a.resize(None)).

public void resize(params long[] new_shape)

Parameters

new_shape long[]

Shape of resized array (one value per dimension).

Remarks

Exceptions

IncorrectShapeException

If this array is not single-segment (contiguous); if growing/shrinking an array that does not own its data or is referenced by another array; or if a dimension is negative.

resize(params ReadOnlySpan<long>)

Change shape and size of this array in-place (see resize(params long[]) for the fill and truncate rules). This is the overload inline values bind (a.resize(2, 3)): the call allocates only the dimension array the new shape keeps.

public void resize(params ReadOnlySpan<long> new_shape)

Parameters

new_shape ReadOnlySpan<long>

Shape of resized array (one value per dimension). Empty is a no-op, as NumPy's a.resize().

Remarks

a.resize() binds this overload. An array argument binds resize(params long[]) instead, which copies it. https://numpy.org/doc/stable/reference/generated/numpy.ndarray.resize.html

Exceptions

IncorrectShapeException

If this array is not single-segment (contiguous); if growing/shrinking an array that does not own its data or is referenced by another array; or if a dimension is negative.

MemoryError

The new element count overflows (NumPy's MemoryError).

roll(int)

Roll array elements along a given axis.

Elements that roll beyond the last position are re-introduced at the first. The array is flattened before shifting, after which the original shape is restored.

public NDArray roll(int shift)

Parameters

shift int

The number of places by which elements are shifted.

Returns

NDArray

Output array, with the same shape as the input.

Remarks

roll(int, int)

Roll array elements along a given axis.

Elements that roll beyond the last position are re-introduced at the first.

public NDArray roll(int shift, int axis)

Parameters

shift int

The number of places by which elements are shifted.

axis int

Axis along which elements are shifted.

Returns

NDArray

Output array, with the same shape as the input.

Remarks

roll(long)

Roll array elements along a given axis.

Elements that roll beyond the last position are re-introduced at the first. The array is flattened before shifting, after which the original shape is restored.

public NDArray roll(long shift)

Parameters

shift long

The number of places by which elements are shifted.

Returns

NDArray

Output array, with the same shape as the input.

Remarks

roll(long, int)

Roll array elements along a given axis.

Elements that roll beyond the last position are re-introduced at the first.

public NDArray roll(long shift, int axis)

Parameters

shift long

The number of places by which elements are shifted.

axis int

Axis along which elements are shifted.

Returns

NDArray

Output array, with the same shape as the input.

Remarks

round(int, NDArray)

Return this array with each element rounded to the given number of decimals (round half to even). Refer to round(NDArray, int, NDArray) for full documentation.

public NDArray round(int decimals = 0, NDArray @out = null)

Parameters

decimals int

Number of decimal places to round to (default 0). Negative values round to positions left of the decimal point.

out NDArray

Alternate output array in which to place the result. It must have the same shape as the expected output.

Returns

NDArray

An array of the same type as this array, containing the rounded values.

Remarks

searchsorted(NDArray, string, NDArray)

Find the indices into this SORTED array where each value in v would be inserted to keep it sorted. Refer to searchsorted(NDArray, NDArray, string, NDArray) for full documentation.

public NDArray searchsorted(NDArray v, string side = "left", NDArray sorter = null)

Parameters

v NDArray

Values to insert.

side string

If "left" (default), the first suitable location is given; if "right", the last.

sorter NDArray

Optional array of integer indices that sort this array (as from argsort).

Returns

NDArray

An array of insertion indices with the same shape as v.

Remarks

searchsorted(double, string, NDArray)

Find the index into this SORTED array where v would be inserted to keep it sorted. Refer to searchsorted(NDArray, int, string, NDArray) for full documentation.

public long searchsorted(double v, string side = "left", NDArray sorter = null)

Parameters

v double

Value to insert.

side string

If "left" (default), the first suitable location is given; if "right", the last.

sorter NDArray

Optional array of integer indices that sort this array (as from argsort).

Returns

long

The insertion index.

Remarks

searchsorted(int, string, NDArray)

Find the index into this SORTED array where v would be inserted to keep it sorted. Refer to searchsorted(NDArray, int, string, NDArray) for full documentation.

public long searchsorted(int v, string side = "left", NDArray sorter = null)

Parameters

v int

Value to insert.

side string

If "left" (default), the first suitable location is given; if "right", the last.

sorter NDArray

Optional array of integer indices that sort this array (as from argsort).

Returns

long

The insertion index.

Remarks

setfield(object, DType, int)

Puts a value into a specified place in a field defined by a dtype — writes value (cast to dtype) into the offset-th byte(s) of each element, leaving the rest of each element untouched. In place. Port of NumPy's ndarray.setfield(val, dtype, offset=0).

public void setfield(object value, DType dtype, int offset = 0)

Parameters

value object

Value(s) to place into the field. A scalar is broadcast; an array must broadcast to this array's shape. Cast to dtype with NumPy's assignment ('unsafe') rule (float → int truncates toward zero). null is Python's None: NaN / nan+nanj / False / 'None' in the field's dtype, int()'s TypeError for an integer field.

dtype DType

The dtype of the field being set (its itemsize must be ≤ this array's itemsize). Null is Python's None, which NumPy's dtype converter reads as the default float64.

offset int

Byte offset of the field within each element.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.setfield.html

setfield is getfield plus an assignment: it builds the same byte-reinterpreting field view and copies value into it. Writeability is checked FIRST (before the dtype/offset validation), matching NumPy's PyArray_SetField.

Exceptions

TypeError

value is null (None) and dtype is an integer (or decimal) dtype.

ValueError

assignment destination is read-only (this array is not writeable), or one of getfield's three dtype/offset ValueErrors.

TypeError

getfield's Cannot get/set field of an object array (a StringDType array or field other than the whole element in its own descriptor, which IS assigned).

NotSupportedException

getfield's refusal of a non-native field descriptor (setfield(1, '>i4'): NumPy stores the value's bytes big-endian, NumSharp has no non-native storage — nothing is written).

setflags(bool?, bool?, bool?)

Set array flags WRITEABLE, ALIGNED and WRITEBACKIFCOPY, respectively — the port of NumPy's ndarray.setflags(write=None, align=None, uic=None) (array_setflags, numpy/_core/src/multiarray/methods.c, NumPy 2.4.2). null leaves a flag untouched; flags are processed in NumPy's order — align, then uic, then write — and an error ROLLS BACK every change made earlier in the same call (probed: setflags(align=False, uic=True) raises with aligned still True).

public void setflags(bool? write = null, bool? align = null, bool? uic = null)

Parameters

write bool?

Describes whether or not the array can be written to. Turning it ON follows NumPy's _IsWriteable rule, evaluated UNCONDITIONALLY (even when the flag is already on — probed: a still-writeable view whose base has since been made read-only is refused, and stays writeable): an array that owns ordinary memory may always be re-enabled; a view may iff its base is writeable (so np.broadcast_to views CAN be re-enabled — writes then alias across the stride-0 axes and reach the source, exactly as in NumPy); an array over foreign read-only memory (an 'r' memmap, a read-only buffer) is refused with NumPy's ValueError("cannot set WRITEABLE flag to True of this array").

align bool?

Describes whether or not the data is aligned properly for its type. False CLEARS the ALIGNED flag (observable in flags: aligned/num/behaved/ carray/farray and the repr all follow); True re-sets it when the memory is aligned and raises NumPy's ValueError("cannot set aligned flag of mis-aligned array to True") when it is not — an array over a caller's buffer at a misaligning byte offset (np.ndarray(shape, buffer=b, offset=3)) or a view of one. Fresh views and copies of an align-cleared array come back ALIGNED when their memory is, as in NumPy (each new array recomputes the flag).

uic bool?

(Write-back-if-copy.) True raises NumPy's ValueError("cannot set WRITEBACKIFCOPY flag to True") — the flag can only be set by NumPy's C-API. False is accepted as a no-op: NumSharp never sets WRITEBACKIFCOPY, and NumPy's side effect of ALSO severing the view's base reference (Py_XDECREF(fa->base) — after which v.base is None and the data can dangle if the owner dies) is deliberately NOT reproduced: BaseStorage roots the owner for the view's lifetime, and detaching it would be a use-after-free hazard with no writeback state to resolve. A documented memory-safety divergence.

Remarks

a.flags.writeable = …, a.flags.aligned = … (no-op result aside) and a.flags["W"/"A"/"X"] = … all route through this method, exactly as NumPy's arrayflags setters call self.arr.setflags(…) (flagsobject.c).

One corner inherits NumSharp's flattened base chain: a view whose DIRECT parent is a read-only intermediate but whose ultimate owner is writeable is re-enabled (NumPy's own array-chain rule does the same — "if ANY base is writeable" — its collapsed .base skips read-only intermediates too; only a non-array buffer boundary pins the exporter's read-only bit, which NumSharp models with WriteProtected on the boundary storage itself).

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.setflags.html

Exceptions

ValueError

align: true on misaligned memory, uic: true, or write: true on an array NumPy's rule refuses (see above).

sort(int?, string, object, bool?, bool?)

Sort this array in place along axis (default last; null flattens, a NumSharp extension). NumPy's ndarray.sort(axis=-1, kind=None, order=None, *, stable=None, descending=False).

public void sort(int? axis = -1, string kind = null, object order = null, bool? stable = null, bool? descending = null)

Parameters

axis int?

Axis to sort along; null flattens (NumSharp's extension — NumPy's method takes no None).

kind string

The sort algorithm (see sort(NDArray, int?, string, object, bool?, bool?)).

order object

Field names; any value is refused (no NumSharp dtype has fields).

stable bool?

True asks for the stable kind; cannot be combined with kind.

descending bool?

True sorts the largest value first, NaN still last (NumPy 2.5); cannot be combined with kind.

Exceptions

ValueError

An unknown kind, kind given with stable or descending, an order, or a read-only array (sort array is read-only).

AxisError

A string array with an out-of-bounds axis.

RuntimeError

A StringDType array sorted descending (unsupported sort kind).

ValueError

A StringDType line of two or more elements that holds an NA of a descriptor whose NA object is neither a string nor NaN-like (NumPy's Cannot compare null that is not a nan-like value, raised after the lines before it were sorted).

MemoryError

A corrupt StringDType cell (NumPy's MemoryError text).

squeeze(int)

squeeze(NDAxis?) with the axis as one int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so every answer, error, layout and subclass result is that overload's.

public NDArray squeeze(int axis)

Parameters

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

Returns

NDArray

A view of this array with the selected length-one axes removed. Shares memory with this array.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.squeeze.html. The axis is an NDAxis since API-parity batch 4 (2026-11-12); an int? argument converts.

Exceptions

AxisError

An axis is out of range.

ValueError

A selected axis does not have length one, or a tuple names an axis twice (duplicate value in 'axis').

squeeze(int[])

squeeze(NDAxis?) with the axes as an int[]: the overload an int[] binds, and a bare null too (null converts to int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple (new int[0] is ()).

public NDArray squeeze(int[] axis)

Parameters

axis int[]

The axes as NumPy's tuple, or null for None.

Returns

NDArray

A view of this array with the selected length-one axes removed. Shares memory with this array.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.squeeze.html. The axis is an NDAxis since API-parity batch 4 (2026-11-12); an int? argument converts.

Exceptions

AxisError

An axis is out of range.

ValueError

A selected axis does not have length one, or a tuple names an axis twice (duplicate value in 'axis').

squeeze(NDAxis?)

Remove axes of length one from this array (NumPy's ndarray.squeeze(axis=None)). Refer to squeeze(NDArray, NDAxis?) for full documentation.

public NDArray squeeze(NDAxis? axis = null)

Parameters

axis NDAxis?

Selects the entries of length one to remove: null (None, the default) removes all length-one axes; one axis or a tuple ((0, 2), new[] { 0, 2 }) removes those, and the empty tuple none. Selecting an axis whose length is not one raises.

Returns

NDArray

A view of this array with the selected length-one axes removed. Shares memory with this array.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.squeeze.html. The axis is an NDAxis since API-parity batch 4 (2026-11-12); an int? argument converts.

Exceptions

AxisError

An axis is out of range.

ValueError

A selected axis does not have length one, or a tuple names an axis twice (duplicate value in 'axis').

std(int, DType, NDArray, int, bool, NDArray, NDArray)

std(NDAxis?, DType, NDArray, int, bool, NDArray, NDArray) with the axis as one int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so every answer, error, layout and subclass result is that overload's.

public NDArray std(int axis, DType dtype = null, NDArray @out = null, int ddof = 0, bool keepdims = false, NDArray where = null, NDArray mean = null)

Parameters

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

dtype DType

The loop of both sums, or null for NumPy's default.

out NDArray

The float or complex array the result is written into and returned. Footgun: the THIRD positional parameter, as in NumPy; write ddof: and keepdims: by name.

ddof int

Delta degrees of freedom: the variance divides by max(N - ddof, 0).

keepdims bool

Keep the reduced axes as length-1 dimensions.

where NDArray

A bool mask of the elements each output takes, or null.

mean NDArray

The mean to subtract as given (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)), or null to compute it.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) when the result has no dimensions.

Remarks

The member keeps the plain-array meaning for a numpy.matrix object reached through an NDArray reference.

Exceptions

AxisError

axis is out of bounds.

ValueError

A read-only or misshapen out. Also a tuple that names an axis twice (duplicate value in 'axis').

TypeError

An integer or bool dtype or out with a result that has dimensions (NumPy's sqrt output-cast error).

ArgumentException

A non-bool where.

IncorrectShapeException

out, where or mean does not broadcast.

TypeError

A boolean subtraction; a C# scalar passed as out; NumPy's text refusals.

std(int[], DType, NDArray, int, bool, NDArray, NDArray)

std(NDAxis?, DType, NDArray, int, bool, NDArray, NDArray) with the axes as an int[]: the overload an int[] binds, and a bare null too (null converts to int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple (new int[0] is ()).

public NDArray std(int[] axis, DType dtype = null, NDArray @out = null, int ddof = 0, bool keepdims = false, NDArray where = null, NDArray mean = null)

Parameters

axis int[]

The axes as NumPy's tuple, or null for None.

dtype DType

The loop of both sums, or null for NumPy's default.

out NDArray

The float or complex array the result is written into and returned. Footgun: the THIRD positional parameter, as in NumPy; write ddof: and keepdims: by name.

ddof int

Delta degrees of freedom: the variance divides by max(N - ddof, 0).

keepdims bool

Keep the reduced axes as length-1 dimensions.

where NDArray

A bool mask of the elements each output takes, or null.

mean NDArray

The mean to subtract as given (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)), or null to compute it.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) when the result has no dimensions.

Remarks

The member keeps the plain-array meaning for a numpy.matrix object reached through an NDArray reference.

Exceptions

AxisError

axis is out of bounds.

ValueError

A read-only or misshapen out. Also a tuple that names an axis twice (duplicate value in 'axis').

TypeError

An integer or bool dtype or out with a result that has dimensions (NumPy's sqrt output-cast error).

ArgumentException

A non-bool where.

IncorrectShapeException

out, where or mean does not broadcast.

TypeError

A boolean subtraction; a C# scalar passed as out; NumPy's text refusals.

std(NDAxis?, DType, NDArray, int, bool, NDArray, NDArray)

NumPy's ndarray.std(axis=None, dtype=None, out=None, ddof=0, *, keepdims=<no value>, where=<no value>, mean=<no value>) (_methods._std): the standard deviation over axis. This is the only overload: NumPy's whole signature (np-layer dtype plan P10, D10); the parameters behave as std(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)'s. There is no correction=: NumPy 2.4.2's method refuses it; std(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?) takes it.

public NDArray std(NDAxis? axis = null, DType dtype = null, NDArray @out = null, int ddof = 0, bool keepdims = false, NDArray where = null, NDArray mean = null)

Parameters

axis NDAxis?

The axis to compute along (negative counts from the end); null uses every element. A tuple ((0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).

dtype DType

The loop of both sums, or null for NumPy's default.

out NDArray

The float or complex array the result is written into and returned. Footgun: the THIRD positional parameter, as in NumPy; write ddof: and keepdims: by name.

ddof int

Delta degrees of freedom: the variance divides by max(N - ddof, 0).

keepdims bool

Keep the reduced axes as length-1 dimensions.

where NDArray

A bool mask of the elements each output takes, or null.

mean NDArray

The mean to subtract as given (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)), or null to compute it.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) when the result has no dimensions.

Remarks

The member keeps the plain-array meaning for a numpy.matrix object reached through an NDArray reference.

Exceptions

AxisError

axis is out of bounds.

ValueError

A read-only or misshapen out. Also a tuple that names an axis twice (duplicate value in 'axis').

TypeError

An integer or bool dtype or out with a result that has dimensions (NumPy's sqrt output-cast error).

ArgumentException

A non-bool where.

IncorrectShapeException

out, where or mean does not broadcast.

TypeError

A boolean subtraction; a C# scalar passed as out; NumPy's text refusals.

sum(int, DType, NDArray, bool, object, NDArray)

sum(NDAxis?, DType, NDArray, bool, object, NDArray) with the axis as one int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so every answer, error, layout and subclass result is that overload's.

public NDArray sum(int axis, DType dtype = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)

Parameters

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

dtype DType

The accumulator and result dtype, or null for NumPy's default (NEP 50's accumulator; promote_types(out, this) with an out).

out NDArray

The array the sum is written into and returned. Footgun: the THIRD positional parameter, as in NumPy, so write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions.

initial object

The value every sum starts from instead of 0 (see sum(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray)), or null.

where NDArray

A bool mask of the elements to sum, or null (the C# true literal is NumPy's default).

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a sum over every axis without keepdims.

Remarks

The member keeps the plain-array meaning for a numpy.matrix object reached through an NDArray reference (an NDMatrix reference binds NDMatrix.sum(int?, DType, NDMatrix)).

Exceptions

TypeError

A C# scalar passed as out; an initial the loop cannot take; NumPy's text refusals.

ValueError

A read-only or misshapen out; a mask with more axes; an unconvertible initial. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

out or where does not broadcast.

OverflowError

initial does not fit an integer loop.

sum(int[], DType, NDArray, bool, object, NDArray)

sum(NDAxis?, DType, NDArray, bool, object, NDArray) with the axes as an int[]: the overload an int[] binds, and a bare null too (null converts to int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple (new int[0] is ()).

public NDArray sum(int[] axis, DType dtype = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)

Parameters

axis int[]

The axes as NumPy's tuple, or null for None.

dtype DType

The accumulator and result dtype, or null for NumPy's default (NEP 50's accumulator; promote_types(out, this) with an out).

out NDArray

The array the sum is written into and returned. Footgun: the THIRD positional parameter, as in NumPy, so write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions.

initial object

The value every sum starts from instead of 0 (see sum(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray)), or null.

where NDArray

A bool mask of the elements to sum, or null (the C# true literal is NumPy's default).

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a sum over every axis without keepdims.

Remarks

The member keeps the plain-array meaning for a numpy.matrix object reached through an NDArray reference (an NDMatrix reference binds NDMatrix.sum(int?, DType, NDMatrix)).

Exceptions

TypeError

A C# scalar passed as out; an initial the loop cannot take; NumPy's text refusals.

ValueError

A read-only or misshapen out; a mask with more axes; an unconvertible initial. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

out or where does not broadcast.

OverflowError

initial does not fit an integer loop.

sum(NDAxis?, DType, NDArray, bool, object, NDArray)

NumPy's ndarray.sum(axis=None, dtype=None, out=None, *, keepdims=<no value>, initial=<no value>, where=<no value>) (_methods._sum, i.e. np.add.reduce): the sum of the elements over axis. This is the only overload: NumPy's whole signature (np-layer dtype plan P10, D10); the parameters behave as sum(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray)'s.

public NDArray sum(NDAxis? axis = null, DType dtype = null, NDArray @out = null, bool keepdims = false, object initial = null, NDArray where = null)

Parameters

axis NDAxis?

The axis to sum over (negative counts from the end); null sums every element. A tuple ((0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).

dtype DType

The accumulator and result dtype, or null for NumPy's default (NEP 50's accumulator; promote_types(out, this) with an out).

out NDArray

The array the sum is written into and returned. Footgun: the THIRD positional parameter, as in NumPy, so write keepdims: true by name.

keepdims bool

Keep the reduced axes as length-1 dimensions.

initial object

The value every sum starts from instead of 0 (see sum(NDArray, NDAxis?, DType, NDArray, bool, object, NDArray)), or null.

where NDArray

A bool mask of the elements to sum, or null (the C# true literal is NumPy's default).

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) for a sum over every axis without keepdims.

Remarks

The member keeps the plain-array meaning for a numpy.matrix object reached through an NDArray reference (an NDMatrix reference binds NDMatrix.sum(int?, DType, NDMatrix)).

Exceptions

TypeError

A C# scalar passed as out; an initial the loop cannot take; NumPy's text refusals.

ValueError

A read-only or misshapen out; a mask with more axes; an unconvertible initial. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

AxisError

axis is out of bounds.

IncorrectShapeException

out or where does not broadcast.

OverflowError

initial does not fit an integer loop.

swapaxes(int, int)

Interchange two axes of an array.

public NDArray swapaxes(int axis1, int axis2)

Parameters

axis1 int

First axis.

axis2 int

Second axis.

Returns

NDArray

Remarks

take(NDArray, int?, NDArray, string)

Return the elements at indices taken along an axis. Refer to take(NDArray, NDArray, int?, NDArray, string) for full documentation.

public NDArray take(NDArray indices, int? axis = null, NDArray @out = null, string mode = "raise")

Parameters

indices NDArray

Indices of the values to extract. Integer arrays and a single C# integer (a 0-d index) convert implicitly.

axis int?

The axis over which to select values. The default (null) works over the flattened array.

out NDArray

Optional output array of the right shape to hold the result.

mode string

How out-of-bounds indices behave: "raise" (default), "wrap", or "clip".

Returns

NDArray

The returned array has the same type as this array.

Remarks

to_device(string, object)

Array-API device transfer. NumSharp has only the CPU device, so the sole accepted target is "cpu", for which the SAME array is returned with no copy — matching NumPy, which returns self. Any other device raises.

public NDArray to_device(string device, object stream = null)

Parameters

device string

Target device. Must be "cpu".

stream object

Accepted for Array-API signature parity; must be null (NumSharp models no streams).

Returns

NDArray

This array, unchanged.

Remarks

Exceptions

ArgumentNullException

If device is null (NumPy raises TypeError).

ValueError

If stream is non-null (The stream argument in to_device() is not supported), or device is not "cpu" (Unsupported device: gpu. Only 'cpu' is accepted.): NumPy's ValueError, in that order.

tobytes(char)

Construct a byte array containing the raw data bytes of the array in the requested memory order (default C-order). Mirrors NumPy's ndarray.tobytes(order='C'): the result is the logical array (strides, offset and broadcasting resolved), NOT the raw underlying buffer. A view whose memory does not already lay its logical elements out in the requested order (sliced/strided/transposed/broadcast, or C-order requested on an F-contiguous view and vice-versa) is materialized into a fresh contiguous buffer first, so the returned length is always size * dtypesize.

public byte[] tobytes(char order = 'C')

Parameters

order char

Controls the memory layout of the byte output:

  • 'C' - C-order (row-major). Default.
  • 'F' - F-order (column-major).
  • 'A' - "Any": 'F' if this array is F-contiguous (and not C-contiguous), else 'C'.
  • 'K' - accepted for NumPy parity; resolves to 'C' for the numeric dtypes NumSharp supports (NumPy copies into a C-contiguous destination for tobytes('K')).

Returns

byte[]

A fresh, detached byte array of length size * dtypesize.

Remarks

Exceptions

ValueError

order is not one of C/F/A/K, either case (order must be one of 'C', 'F', 'A', or 'K' (got 'Z')): checked first, so an empty array refuses it too.

tofile(Stream, string, string)

Write the array to an open Stream as binary (default) or text. The stream is written from its current position and left open (the caller owns it), matching NumPy's file-object tofile. Data is always in C (row-major) order.

public void tofile(Stream stream, string sep = "", string format = "%s")

Parameters

stream Stream

An open, writeable stream.

sep string

Separator between items for text output; "" (default) writes binary. It is written as its UTF-8 bytes, as NumPy writes the C string. Null is Python's None, which NumPy refuses.

format string

Python-style % format for text output (default "%s"): each element is written as format % (item,) with the Python object NumPy's getitem returns. Null is Python's None, which NumPy refuses.

Remarks

Text mode is NumPy's PyArray_ToFile: for each element in C order, str(item) (format "" or "%s") or format % (item,), then the separator except after the last. item is a Python float for every float dtype (a float32 0.1 writes 0.10000000149011612), an int, a bool (an int to Python's %: '%x' of True is 1), a complex, a str / bytes, or a StringDType element (a str, or the NA object). NumSharp's Char elements are ints (a uint16) and its Decimal elements floats.

Each element's text is written as ASCII (NumPy's PyUnicode_AsASCIIString); a non-ASCII text — a string element, a %c past 127, non-ASCII literal text in the format — raises CPython's UnicodeEncodeError, after the elements before it are written. (NumPy 2.4.2 does not check that encode's result and crashes the process there.)

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.tofile.html

Exceptions

ArgumentNullException

stream is null (after the checks of sep and format, which NumPy's argument parsing makes first).

ValueError

sep or format holds a NUL (embedded null character); a malformed format (incomplete format, unsupported format character 'y' (0x79) at index 1); a NaN under an integer conversion.

UnicodeEncodeError

sep or format holds a lone surrogate (CPython's UTF-8 error); an element's text is not ASCII.

TypeError

A null sep or format (tofile() argument 2 must be str, not None, argument 3 for the format), checked before anything is written; or CPython's TypeError of format % (item,), unwrapped as NumPy leaves it: not enough arguments for format string, %x format: an integer is required, not float, * wants int.

OverflowError

CPython's OverflowError: an infinity under an integer conversion, a %c code point out of range, a * width past a C ssize_t.

OSError

Binary mode over a StringDType array.

tofile(string, string, string)

Write the array to a file as binary (default) or text.

Data is always written in C (row-major) order, independent of the array's own layout — a sliced / strided / transposed / broadcast view writes its logical elements, NOT the raw underlying buffer. The data produced can be recovered with fromfile(string, DType, long, string, long, NDArray).

public void tofile(string fid, string sep = "", string format = "%s")

Parameters

fid string

A filename. The file is created (truncated if it exists).

sep string

Separator between items for text output. If "" (empty, the default) a binary file is written, equivalent to stream.Write(a.tobytes('C')). Null is Python's None, which NumPy refuses.

format string

Python-style % format string for text output (ignored in binary mode). Each entry is written as format % (item,), where item is the Python object NumPy's getitem returns (a float for every float dtype, an int, a bool, a complex, a str), with CPython's rules and errors. "%s" (the default) and "" write str(item) (e.g. 1.5, (1+2j), True). Null is Python's None, which NumPy refuses.

Remarks

sep and format are checked before the file is opened, as NumPy's argument parsing checks them: neither may be null (None) or hold a NUL or a lone surrogate, so a bad one creates no file and leaves an existing one as it is.

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.tofile.html

Exceptions

ValueError

sep or format holds a NUL (embedded null character), or a malformed format / a NaN under an integer conversion (see the stream overload).

UnicodeEncodeError

sep or format holds a lone surrogate, or an element's text is not ASCII (see the stream overload).

TypeError

A null sep or format (NumPy's "s" converter: tofile() argument 2 must be str, not None, argument 3 for the format), or a conversion the elements do not take (see the stream overload).

OverflowError

See the stream overload.

OSError

Binary mode over a StringDType array.

tolist()

Return the array as an (possibly nested) list.

public object tolist()

Returns

object

The possibly nested list of array elements.

  • For 0-d arrays (scalars): returns the scalar value itself
  • For 1-d arrays: returns List<object> of elements
  • For n-d arrays: returns nested List<object> structures

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.tolist.html

Copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible builtin Python type, via the item function.

If a.ndim is 0, then since the depth of the nested list is 0, it will not be a list at all, but a simple Python scalar.

NumPy's PyArray_ToList / recursive_tolist: the walk follows the strides from the first element (any layout — strided, transposed, reversed, broadcast — with no copy and no per-element index arithmetic), one list per axis position, and each innermost row is read by one GetItems(long, long, Span<object>) call into the row's list. Each element is what item(long) returns for it (the storage's getitem): the boxed CLR value of a numeric element, a string / byte[] of a U / S element, the text or the NA object of a StringDType element. An element that cannot be read raises at the first one in C order, and the half-built lists are dropped, as NumPy drops its own.

The walk replaced an item(long) call per element (a bounds check, a dtype switch and, for a non-contiguous array, a coordinate array per element) and a sub-array view per outer index: over 100K text elements of 20–60 characters a tolist() went 46.5 → 25.2 ns per element for S, 90.9 → 60.0 for U and 79.1 → 46.3 for StringDType (NumPy 58.3 / 92.8 / 100.2), at 4–12 characters 34.0 → 23.9, 38.7 → 29.7 and 49.6 → 30.8 (NumPy 39.7 / 54.2 / 74.1). What remains is the object every element becomes: a text of 300–500 characters stays at or below NumPy (S / U / StringDType about 0.97 / 0.83 / 0.69 of its speed, pinned), because allocating 100K such .NET strings (UTF-16, two bytes a character) and keeping them alive through the gen0 / gen1 collections that copy them costs about what NumPy's whole tolist costs (its compact one-byte str, reference-counted, is never copied).

NDAnchoredAttribute (lost-anchor site LT29): each innermost row is read through a raw pointer while one object per element is allocated, and nothing but this array keeps the buffer alive, so the receiver is rooted to the end. Without it a.copy().tolist() left the copy reachable from nothing during the walk: a collection could finalize its memory block and the rest of the row read freed memory.

Exceptions

SystemError

A U element holds a unit above U+10FFFF (NumPy raises the same).

OutOfMemoryException

A StringDType element's cell is corrupt (NumPy's Failed to load string in StringDType getitem) or its text is too long for a .NET string, or an axis is longer than a .NET list can hold (MaxLength elements).

trace(int, int, int, DType, NDArray)

Return the sum along diagonals of the array. Refer to trace(NDArray, int, int, int, DType, NDArray) for full documentation.

public NDArray trace(int offset = 0, int axis1 = 0, int axis2 = 1, DType dtype = null, NDArray @out = null)

Parameters

offset int

Offset of the diagonal from the main diagonal. Can be positive or negative. Defaults to 0.

axis1 int

First axis of the 2-D sub-arrays from which the diagonals are taken. Defaults to 0.

axis2 int

Second axis of the 2-D sub-arrays from which the diagonals are taken. Defaults to 1.

dtype DType

Output dtype. null (default) preserves the dtype, promoting integer dtypes narrower than int64 to int64.

out NDArray

Optional output array whose shape must equal the natural reduction output.

Returns

NDArray

The sum along the diagonals. For a 2-D array this is a 0-d scalar.

Remarks

transpose(params int[])

Permute the dimensions of an array (NumPy's a.transpose(*axes)): a view with the dimensions and strides reordered.

public NDArray transpose(params int[] axes)

Parameters

axes int[]

NumPy's *axes: the permutation as separate integers (a.transpose(1, 0)) or as one array (NumPy's tuple, a.transpose(new[] {1, 0})); no argument, an empty array or null reverses the dimensions.

Returns

NDArray

a with its axes permuted. A view is returned whenever possible.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.transpose.html

One member with NumPy's call shapes: params makes a.transpose(2, 0, 1) compile, which the former transpose(int[] premute = null) refused (CS1501). The empty case is a C# limit: a call without arguments arrives as an EMPTY array, so an empty array reads as NumPy's no-argument call (reverse) - NumPy's a.transpose(()), an explicit empty tuple, raises "axes don't match array" for ndim > 0, and C# cannot tell the two apart. transpose(NDArray, int[]) keeps NumPy's reading of an empty permutation.

Exceptions

ValueError

axes does not have one entry per dimension (axes don't match array), or repeats an axis (repeated axis in transpose).

AxisError

An entry of axes is out of bounds.

unique(bool, bool, bool, int?, bool, bool)

Find the unique elements of an array with full NumPy keyword argument support.

Returns sorted unique elements; optionally returns first-occurrence indices, reconstruction indices, and counts. Supports axis-aware uniqueness.

public NDArray[] unique(bool return_index, bool return_inverse = false, bool return_counts = false, int? axis = null, bool equal_nan = true, bool sorted = true)

Parameters

return_index bool

Also return indices of ar (along axis, if specified) that give the unique values.

return_inverse bool

Also return indices of the unique array that can be used to reconstruct ar.

return_counts bool

Also return the number of times each unique value comes up.

axis int?

Axis to operate on. If null (default), the array is flattened.

equal_nan bool

If true (default), all NaN values are treated as equal so only one appears in the output. If false, each NaN is treated as unique.

sorted bool

If true (default), the unique elements are sorted (NumPy 2.3). NumSharp always returns sorted output — NumPy's sorted=False hash order for integer/complex values and for text is platform-specific and not reproducible in C# — so this parameter is accepted for API parity but does not change the result (spec-compliant).

Returns

NDArray[]

An array of NDArrays in order: [values, index?, inverse?, counts?]. With axis null the inverse has the input's shape (NumPy's inv_idx.reshape(ar.shape): () for a 0-d input, (0, 3) for an empty (0, 3) one).

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.unique.html (the computation is this array's Unique(NDArray, bool, bool, bool, int?, bool, bool); the internals are reclaimed at its return, the outputs are kept).

Exceptions

AxisError

axis is out of range.

TypeError

A StringDType array of two or more dimensions with an axis (NumPy's structured path refuses it).

ValueError

A StringDType array whose NA object is neither NaN-like nor a string, where NumPy's sort compares an NA. Text computes NumPy's answer: fixed-width text through NumPy's statements, StringDType through NumPy's flat path (see Unique(NDArray, bool, bool, bool, int?, bool, bool)).

unique(int?, bool, bool)

Find the unique elements of an array (bare-return form).

Returns the sorted unique elements. Mirrors NumPy's single-array return (no return_* flag): supports axis-aware uniqueness and the equal_nan/ sorted keywords. For first-occurrence indices / reconstruction indices / counts, use unique(bool, bool, bool, int?, bool, bool).

public NDArray unique(int? axis = null, bool equal_nan = true, bool sorted = true)

Parameters

axis int?

Axis to operate on. If null (default), the array is flattened.

equal_nan bool

If true (default), all NaNs collapse to one output value.

sorted bool

Accepted for API parity; NumSharp always returns sorted output.

Returns

NDArray

The sorted unique values.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.unique.html (the computation is this array's Unique(NDArray, bool, bool, bool, int?, bool, bool) without return flags, of which this member returns the values; the internals are reclaimed at its return).

Exceptions

AxisError

axis is out of range.

TypeError

A StringDType array of two or more dimensions with an axis (NumPy's structured path refuses it).

ValueError

A StringDType array whose NA object is neither NaN-like nor a string, with an NA among two or more distinct values (NumPy's sort refuses to compare it).

unique<T>()

The sorted distinct values of this array, found with a hash set: a legacy helper that no NumSharp code calls, kept for subclasses (it is protected on a public, unsealed class). np.unique does not run it and its answer is not NumPy's in the cases listed under remarks; call unique(int?, bool, bool) for NumPy's answer.

protected NDArray unique<T>() where T : unmanaged, IComparable<T>

Returns

NDArray

A new 1-D array of the distinct values in ascending order. Values that Default calls equal are one value: every NaN is one value, and so are -0.0 and +0.0; the one kept is the first met in C order, with its bits.

Type Parameters

T

The CLR type of the array's dtype. The elements are read as T without a check, so any other type reinterprets the bytes.

Remarks

Where the answer differs from NumPy's np.unique:

  • a float16 NaN sorts first, because CompareTo(Half) orders a NaN below every value (float32 and float64 put it last, as NumPy does);
  • the NaN kept has the bits of the first NaN met, where NumPy's sort writes the positive quiet NaN for float32 and float64.

A non-contiguous array is read through flat, a raveled copy that is not disposed: its buffer returns to the pool only when the finalizer runs. https://numpy.org/doc/stable/reference/generated/numpy.unique.html

var(int, DType, NDArray, int, bool, NDArray, NDArray)

var(NDAxis?, DType, NDArray, int, bool, NDArray, NDArray) with the axis as one int: the overload a C# integer binds (its identity conversion beats NDAxis' implicit one), forwarding to the NDAxis form, so every answer, error, layout and subclass result is that overload's.

public NDArray var(int axis, DType dtype = null, NDArray @out = null, int ddof = 0, bool keepdims = false, NDArray where = null, NDArray mean = null)

Parameters

axis int

The axis (NumPy's axis=k; a negative value counts from the end).

dtype DType

The loop of both sums, or null for NumPy's default (float64 for bool / integer input).

out NDArray

The array the variance is written into and returned (NumPy hands it to the last sum only). Footgun: the THIRD positional parameter, as in NumPy; write ddof: and keepdims: by name.

ddof int

Delta degrees of freedom: the divisor is max(N - ddof, 0).

keepdims bool

Keep the reduced axes as length-1 dimensions.

where NDArray

A bool mask of the elements each output takes, or null.

mean NDArray

The mean to subtract as given (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)), or null to compute it.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) when the result has no dimensions.

Remarks

The member keeps the plain-array meaning for a numpy.matrix object reached through an NDArray reference.

Exceptions

AxisError

axis is out of bounds.

ValueError

A read-only or misshapen out. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

IncorrectShapeException

out, where or mean does not broadcast.

TypeError

A boolean subtraction (a bool input in a bool loop, or a bool mean of a bool input); a C# scalar passed as out; NumPy's text refusals.

var(int[], DType, NDArray, int, bool, NDArray, NDArray)

var(NDAxis?, DType, NDArray, int, bool, NDArray, NDArray) with the axes as an int[]: the overload an int[] binds, and a bare null too (null converts to int[] better than to NDAxis), forwarding to the NDAxis form: a null array is NumPy's None, any other array NumPy's tuple (new int[0] is ()).

public NDArray var(int[] axis, DType dtype = null, NDArray @out = null, int ddof = 0, bool keepdims = false, NDArray where = null, NDArray mean = null)

Parameters

axis int[]

The axes as NumPy's tuple, or null for None.

dtype DType

The loop of both sums, or null for NumPy's default (float64 for bool / integer input).

out NDArray

The array the variance is written into and returned (NumPy hands it to the last sum only). Footgun: the THIRD positional parameter, as in NumPy; write ddof: and keepdims: by name.

ddof int

Delta degrees of freedom: the divisor is max(N - ddof, 0).

keepdims bool

Keep the reduced axes as length-1 dimensions.

where NDArray

A bool mask of the elements each output takes, or null.

mean NDArray

The mean to subtract as given (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)), or null to compute it.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) when the result has no dimensions.

Remarks

The member keeps the plain-array meaning for a numpy.matrix object reached through an NDArray reference.

Exceptions

AxisError

axis is out of bounds.

ValueError

A read-only or misshapen out. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

IncorrectShapeException

out, where or mean does not broadcast.

TypeError

A boolean subtraction (a bool input in a bool loop, or a bool mean of a bool input); a C# scalar passed as out; NumPy's text refusals.

var(NDAxis?, DType, NDArray, int, bool, NDArray, NDArray)

NumPy's ndarray.var(axis=None, dtype=None, out=None, ddof=0, *, keepdims=<no value>, where=<no value>, mean=<no value>) (_methods._var): the variance over axis. This is the only overload: NumPy's whole signature (np-layer dtype plan P10, D10); the parameters behave as var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)'s. There is no correction=: NumPy 2.4.2's method refuses it (_var() got an unexpected keyword argument 'correction'); var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?) takes it.

public NDArray var(NDAxis? axis = null, DType dtype = null, NDArray @out = null, int ddof = 0, bool keepdims = false, NDArray where = null, NDArray mean = null)

Parameters

axis NDAxis?

The axis to compute along (negative counts from the end); null uses every element. A tuple ((0, 2)) reduces every axis it names together, in one pass (NumPy's tuple axis; the empty tuple reduces none, and a tuple item gets no 0-d allowance).

dtype DType

The loop of both sums, or null for NumPy's default (float64 for bool / integer input).

out NDArray

The array the variance is written into and returned (NumPy hands it to the last sum only). Footgun: the THIRD positional parameter, as in NumPy; write ddof: and keepdims: by name.

ddof int

Delta degrees of freedom: the divisor is max(N - ddof, 0).

keepdims bool

Keep the reduced axes as length-1 dimensions.

where NDArray

A bool mask of the elements each output takes, or null.

mean NDArray

The mean to subtract as given (see var(NDArray, NDAxis?, DType, NDArray, int, bool, NDArray, NDArray, int?)), or null to compute it.

Returns

NDArray

out itself when given; else a fresh array — 0-d (NumPy's read-only scalar) when the result has no dimensions.

Remarks

The member keeps the plain-array meaning for a numpy.matrix object reached through an NDArray reference.

Exceptions

AxisError

axis is out of bounds.

ValueError

A read-only or misshapen out. Also a tuple that names an axis twice (duplicate value in 'axis').

ArgumentException

where is not a bool array.

IncorrectShapeException

out, where or mean does not broadcast.

TypeError

A boolean subtraction (a bool input in a bool loop, or a bool mean of a bool input); a C# scalar passed as out; NumPy's text refusals.

view(DType)

New view of array with the same data.

public NDArray view(DType dtype = null)

Parameters

dtype DType

Data-type descriptor of the returned view, e.g., float32 or int16. The default, None, results in the view having the same data-type as a. This argument can also be specified as an ndarray sub-class, which then specifies the type of the returned object (this is equivalent to setting the type parameter).

Returns

NDArray

A view sharing this array's memory, its bytes read as dtype.

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.view.html

A fixed-width string carries its width on the DESCRIPTOR, so a view from or to a string dtype reinterprets by descriptor (AliasAsDescr(DType)): U3 → U1, U1 → uint32, uint8 → S2.

Exceptions

ValueError

NumPy's itemsize errors: a 0-d array changing size, a non-contiguous last axis, a smaller dtype that does not divide the old itemsize (an unsized 'U'/'S' never does), a larger one that does not divide the last axis' byte length.

NotSupportedException

A view in a non-native byte order ('>i4' on a little-endian host, any non-native numeric or string descriptor: NumPy reads such bytes byte-swapped, NumSharp stores every dtype natively — decode them into a native copy with np.frombuffer(a.tobytes(), '>i4')), raised once NumPy's itemsize checks pass (a view NumPy itself refuses raises its ValueError); or a dtype without storage (datetime64 before Stage C).

TypeError

A view from or to a NEP 55 StringDType descriptor other than this array's own descriptor object — an equal but separate instance such as a fresh np.dtype("T") included, as NumPy 2.5 refuses it (NumPy's Cannot change data-type for array of references.).

view(DType, Type)

NumPy's a.view(dtype, type): a new view of this array as the array class type, its bytes read as dtype. NumPy builds the subclass object with the CURRENT dtype — its array_finalize sees that one — and changes the dtype afterwards, so s.view(np.int32, chararray) of an S4 array is an int32 chararray while np.arange(2).view("S8", chararray) raises.

public NDArray view(DType dtype, Type type)

Parameters

dtype DType

The dtype to read the bytes as, or null to keep this array's.

type Type

The array class: typeof(NDArray) (a plain view, also of a chararray or a matrix), typeof(NDCharArray) or typeof(NDMatrix); null is the same as view(DType).

Returns

NDArray

A view sharing this array's memory, of the class asked for (the static type is NDArray).

Remarks

Exceptions

ValueError

type is not an array class (NumPy's Type must be a sub-type of ndarray type), the class's finalize rule refuses this array's CURRENT dtype, or one of NumPy's itemsize errors for dtype.

IncorrectShapeException

A matrix view of more than two axes where one has extent 0.

NotSupportedException

An array class with no NumPy counterpart (NDArray<T>).

TypeError

A view to or from a StringDType descriptor that is not equal to this array's.

view(Type)

NumPy's a.view(type) with one argument: an ARRAY CLASS (typeof(NDArray), typeof(NDCharArray), typeof(NDMatrix)) is the type argument, any other CLR type is the dtype it names (a.view(typeof(float))) — NumPy's rule that a type given as the dtype is the type when it is an ndarray subclass.

public NDArray view(Type type)

Parameters

type Type

An array class, a CLR element type, or null (a view of the same class and dtype).

Returns

NDArray

A view sharing this array's memory, of the class asked for; NDArray is its static type (cast it to reach the class's members, no copy is made).

Remarks

Exceptions

ValueError

The class's finalize rule refuses this array's dtype (np.arange(3).view(typeof(NDCharArray)): Can only create a chararray from string data.; a matrix of more than two axes longer than 1), or one of NumPy's itemsize errors for a dtype.

NotSupportedException

An array class with no NumPy counterpart (NDArray<T>), or a CLR type that names no dtype.

view<T>()

New view of array with the same data.

public NDArray<T> view<T>() where T : unmanaged

Returns

NDArray<T>

The typed view (shares memory with this array; keeps its buffer alive while it lives).

Type Parameters

T

The element type the bytes are read as (the view's dtype).

Remarks

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.view.html

Built as the typed array directly over the alias storage view(DType) would wrap: going through view(typeof(T)).AsGeneric<T>() made a SECOND NDArray over that storage, leaving the first — a counted reference on this array's buffer — to the finalizer.

Exceptions

ValueError

NumPy's itemsize errors: a 0-d array whose itemsize changes, a dtype of a different size over a non-contiguous last axis, a smaller dtype that does not divide the old itemsize, or a larger dtype that does not divide the last axis' byte length.

InvalidOperationException

A view whose byte offset or outer byte stride is not a whole number of new elements (NumSharp keeps strides in elements; NumPy, in bytes, allows it).

TypeError

This array holds NEP 55 StringDType text (Cannot change data-type for array of references.).

vstack(params NDArray[])

Stack arrays in sequence vertically (row wise).
This is equivalent to concatenation along the first axis after 1-D arrays of shape(N,) have been reshaped to(1, N). Rebuilds arrays divided by vsplit.

public NDArray vstack(params NDArray[] tup)

Parameters

tup NDArray[]

The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length.

Returns

NDArray

https://numpy.org/doc/stable/reference/generated/numpy.vstack.html

Operators

operator +(NDArray, NDArray)

public static NDArray operator +(NDArray x, NDArray y)

Parameters

x NDArray
y NDArray

Returns

NDArray

operator +(NDArray, object)

public static NDArray operator +(NDArray left, object right)

Parameters

left NDArray
right object

Returns

NDArray

operator +(NDArray, string)

Concatenation with a C# string (see the type remarks for how the string is read).

public static NDArray operator +(NDArray lhs, string rhs)

Parameters

lhs NDArray

The array.

rhs string

The string, or null.

Returns

NDArray

The result of np.add(lhs, rhs).

Exceptions

TypeError

An S array (NumPy refuses bytes plus str: "ufunc 'add' cannot use operands with types …"), or a numeric array the legacy conversion cannot add to.

IncorrectShapeException

The legacy conversion of rhs does not broadcast.

operator +(object, NDArray)

public static NDArray operator +(object left, NDArray right)

Parameters

left object
right NDArray

Returns

NDArray

operator +(string, NDArray)

Concatenation of a C# string with an array: Python's radd, np.add(lhs, rhs) (see the type remarks).

public static NDArray operator +(string lhs, NDArray rhs)

Parameters

lhs string

The string, or null.

rhs NDArray

The array.

Returns

NDArray

The result of np.add(lhs, rhs), the string first.

Exceptions

TypeError

An S array, or a numeric array the legacy conversion cannot add to.

IncorrectShapeException

The legacy conversion of lhs does not broadcast.

operator &(NDArray, NDArray)

Element-wise bitwise AND operation. For boolean arrays: logical AND. For integer arrays: bitwise AND. Supports broadcasting.

public static NDArray operator &(NDArray lhs, NDArray rhs)

Parameters

lhs NDArray
rhs NDArray

Returns

NDArray

operator &(NDArray, object)

Element-wise bitwise AND with any scalar or array-like.

public static NDArray operator &(NDArray lhs, object rhs)

Parameters

lhs NDArray
rhs object

Returns

NDArray

operator &(object, NDArray)

Element-wise bitwise AND with any scalar or array-like on left.

public static NDArray operator &(object lhs, NDArray rhs)

Parameters

lhs object
rhs NDArray

Returns

NDArray

operator |(NDArray, NDArray)

Element-wise bitwise OR operation. For boolean arrays: logical OR. For integer arrays: bitwise OR. Supports broadcasting.

public static NDArray operator |(NDArray lhs, NDArray rhs)

Parameters

lhs NDArray
rhs NDArray

Returns

NDArray

operator |(NDArray, object)

Element-wise bitwise OR with any scalar or array-like.

public static NDArray operator |(NDArray lhs, object rhs)

Parameters

lhs NDArray
rhs object

Returns

NDArray

operator |(object, NDArray)

Element-wise bitwise OR with any scalar or array-like on left.

public static NDArray operator |(object lhs, NDArray rhs)

Parameters

lhs object
rhs NDArray

Returns

NDArray

operator /(NDArray, NDArray)

public static NDArray operator /(NDArray x, NDArray y)

Parameters

x NDArray
y NDArray

Returns

NDArray

operator /(NDArray, object)

public static NDArray operator /(NDArray left, object right)

Parameters

left NDArray
right object

Returns

NDArray

operator /(object, NDArray)

public static NDArray operator /(object left, NDArray right)

Parameters

left object
right NDArray

Returns

NDArray

operator ==(NDArray, NDArray)

NumPy's a == b (array_richcompare): the elementwise equal ufunc over the broadcast operands, as a typed bool array — NOT a reference or value-equality test. Where the ufunc has no loop for a string operand (text against numbers, two string classes that do not compare) the answer is False everywhere instead of an error, as NumPy's operator gives it.

public static NDArray<bool> operator ==(NDArray lhs, NDArray rhs)

Parameters

lhs NDArray

The left operand; null compares as C# null (see remarks).

rhs NDArray

The right operand; null compares as C# null.

Returns

NDArray<bool>

The bool comparison in the broadcast shape; a 0-d bool for a null operand; an empty bool array of lhs's shape when lhs is uninitialized (has no shape at all).

Remarks

Footgun: if (a == b) does not compile into an equality test — the result is an array. Use array_equal(NDArray, bool) (or np.all(a == b)) for one bool, and ReferenceEquals(object, object) for identity.

The null answers are C#'s protocol, not NumPy's (Python's None becomes an object array there): two nulls are a 0-d True, one null a 0-d False. They and the uninitialized-array answer stay here; the comparison itself is RichCompareEquality(NDArray, NDArray, bool), the engine's (the np-layer dtype plan, P1c).

Not scoped: the engine returns a bool-typed result that AsGeneric passes through, so this hot path mints no temporary to reclaim. On the rare null and uninitialized answers MakeGeneric aliases a fresh untyped array, which is left to the finalizer, as before.

Exceptions

IncorrectShapeException

The operands do not broadcast (NumPy's ValueError text).

operator ==(NDArray, object)

Element-wise equal comparison with scalar (==).

public static NDArray<bool> operator ==(NDArray lhs, object rhs)

Parameters

lhs NDArray
rhs object

Returns

NDArray<bool>

operator ==(NDArray, string)

Element-wise equality with a C# string (see the type remarks for how the string is read).

public static NDArray<bool> operator ==(NDArray lhs, string rhs)

Parameters

lhs NDArray

The array.

rhs string

The string, or null.

Returns

NDArray<bool>

The bool result of lhs == rhs.

Exceptions

IncorrectShapeException

The legacy conversion of rhs does not broadcast with lhs (a non-text array).

operator ==(object, NDArray)

Element-wise equal comparison with scalar on left (==).

public static NDArray<bool> operator ==(object lhs, NDArray rhs)

Parameters

lhs object
rhs NDArray

Returns

NDArray<bool>

operator ==(string, NDArray)

Element-wise equality of a C# string with an array: Python's reflection rhs == lhs (see the type remarks).

public static NDArray<bool> operator ==(string lhs, NDArray rhs)

Parameters

lhs string

The string, or null.

rhs NDArray

The array.

Returns

NDArray<bool>

The bool result of lhs == rhs.

Exceptions

IncorrectShapeException

The legacy conversion of lhs does not broadcast.

operator ^(NDArray, NDArray)

Element-wise bitwise XOR operation. For boolean arrays: logical XOR. For integer arrays: bitwise XOR. Supports broadcasting.

public static NDArray operator ^(NDArray lhs, NDArray rhs)

Parameters

lhs NDArray
rhs NDArray

Returns

NDArray

operator ^(NDArray, object)

Element-wise bitwise XOR with any scalar or array-like.

public static NDArray operator ^(NDArray lhs, object rhs)

Parameters

lhs NDArray
rhs object

Returns

NDArray

operator ^(object, NDArray)

Element-wise bitwise XOR with any scalar or array-like on left.

public static NDArray operator ^(object lhs, NDArray rhs)

Parameters

lhs object
rhs NDArray

Returns

NDArray

explicit operator Array(NDArray)

public static explicit operator Array(NDArray nd)

Parameters

nd NDArray

Returns

Array

explicit operator bool(NDArray)

NumPy's bool(arr) (array_nonzero): the truth of the ONLY element of a one-element array of any rank ((bool)np.array(new[,] { { 0.0 } }) is False) — nonzero for a number (a NaN is True), either part nonzero for a complex ((bool)np.array(1j) is True), non-empty for a text. A larger or an empty array is ambiguous and refused with NumPy's two ValueErrors (parity QA-14: every N-D array was refused with the numeric conversions' 0-d rule).

public static explicit operator bool(NDArray nd)

Parameters

nd NDArray

The array.

Returns

bool

The element's truth.

Exceptions

ValueError

More than one element (The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()) or none (The truth value of an empty array is ambiguous. Use array.size > 0 to check that an array is not empty.).

explicit operator byte(NDArray)

NumPy's int(arr) as a uint8, checked (see ToCheckedInteger<T>(NDArray, NPTypeCode)): a negative value raises instead of wrapping.

public static explicit operator byte(NDArray nd)

Parameters

nd NDArray

A 0-d array.

Returns

byte

The element as a byte, exact.

Exceptions

TypeError

nd is not 0-d (only 0-dimensional arrays can be converted to Python scalars), or a complex element.

ValueError

A float NaN, or a text that is not an integer literal.

OverflowError

A float infinity, or a value outside uint8.

explicit operator char(NDArray)

NumPy's int(arr) as a UTF-16 code unit, checked against uint16's range (NumSharp's char lane; see ToCheckedInteger<T>(NDArray, NPTypeCode)).

public static explicit operator char(NDArray nd)

Parameters

nd NDArray

A 0-d array.

Returns

char

The element as a char, exact.

Exceptions

TypeError

nd is not 0-d (only 0-dimensional arrays can be converted to Python scalars), or a complex element.

ValueError

A float NaN, or a text that is not an integer literal.

OverflowError

A float infinity, or a value outside [0, 65535].

explicit operator decimal(NDArray)

The element as a decimal (NumSharp's lane; NumPy has none), through the cast astype runs (ChangeType<TOut>(object)). Footgun: a float NaN, an infinity or a magnitude decimal cannot hold converts to 0, NumSharp's decimal convention, not an error.

public static explicit operator decimal(NDArray nd)

Parameters

nd NDArray

A 0-d array.

Returns

decimal

The element as a decimal.

Exceptions

TypeError

nd is not 0-d (only 0-dimensional arrays can be converted to Python scalars).

TypeError

A complex element (CPython's float() text).

ValueError

A text that is not a float literal.

explicit operator double(NDArray)

NumPy's float(arr).

public static explicit operator double(NDArray nd)

Parameters

nd NDArray

A 0-d array.

Returns

double

The element as a double.

Exceptions

TypeError

nd is not 0-d (only 0-dimensional arrays can be converted to Python scalars).

TypeError

A complex element (CPython's float() text).

ValueError

A text that is not a float literal.

explicit operator Half(NDArray)

NumPy's float(arr) rounded to float16 (an out-of-range value is ±inf).

public static explicit operator Half(NDArray nd)

Parameters

nd NDArray

A 0-d array.

Returns

Half

The element as a Half.

Exceptions

TypeError

nd is not 0-d (only 0-dimensional arrays can be converted to Python scalars).

TypeError

A complex element (CPython's float() text).

ValueError

A text that is not a float literal.

explicit operator short(NDArray)

NumPy's int(arr) as an int16, checked (see ToCheckedInteger<T>(NDArray, NPTypeCode)).

public static explicit operator short(NDArray nd)

Parameters

nd NDArray

A 0-d array.

Returns

short

The element as a short, exact.

Exceptions

TypeError

nd is not 0-d (only 0-dimensional arrays can be converted to Python scalars), or a complex element.

ValueError

A float NaN, or a text that is not an integer literal.

OverflowError

A float infinity, or a value outside int16.

explicit operator int(NDArray)

NumPy's int(arr) as an int32, checked (see ToCheckedInteger<T>(NDArray, NPTypeCode)): (int)np.array(-3.7) is -3, NaN / inf / 3e9 raise.

public static explicit operator int(NDArray nd)

Parameters

nd NDArray

A 0-d array.

Returns

int

The element as an int, exact.

Exceptions

TypeError

nd is not 0-d (only 0-dimensional arrays can be converted to Python scalars), or a complex element.

ValueError

A float NaN, or a text that is not an integer literal.

OverflowError

A float infinity, or a value outside int32.

explicit operator long(NDArray)

NumPy's int(arr) as an int64, checked (see ToCheckedInteger<T>(NDArray, NPTypeCode)): uint64 max and 1e300 raise instead of returning -1 / long.MinValue.

public static explicit operator long(NDArray nd)

Parameters

nd NDArray

A 0-d array.

Returns

long

The element as a long, exact.

Exceptions

TypeError

nd is not 0-d (only 0-dimensional arrays can be converted to Python scalars), or a complex element.

ValueError

A float NaN, or a text that is not an integer literal.

OverflowError

A float infinity, or a value outside int64.

explicit operator Complex(NDArray)

NumPy's complex(arr): any numeric element (a real one gets a zero imaginary part).

public static explicit operator Complex(NDArray nd)

Parameters

nd NDArray

A 0-d array.

Returns

Complex

The element as a Complex.

Exceptions

TypeError

nd is not 0-d (only 0-dimensional arrays can be converted to Python scalars).

TypeError

A text element (Unable to convert dtype('<U2') to complex).

explicit operator sbyte(NDArray)

NumPy's int(arr) as an int8, checked (see ToCheckedInteger<T>(NDArray, NPTypeCode)).

public static explicit operator sbyte(NDArray nd)

Parameters

nd NDArray

A 0-d array.

Returns

sbyte

The element as an sbyte, exact.

Exceptions

TypeError

nd is not 0-d (only 0-dimensional arrays can be converted to Python scalars), or a complex element.

ValueError

A float NaN, or a text that is not an integer literal.

OverflowError

A float infinity, or a value outside int8.

explicit operator float(NDArray)

NumPy's float(arr) rounded to float32 (an out-of-range value is ±inf, as NumPy's float32 of a Python float).

public static explicit operator float(NDArray nd)

Parameters

nd NDArray

A 0-d array.

Returns

float

The element as a float.

Exceptions

TypeError

nd is not 0-d (only 0-dimensional arrays can be converted to Python scalars).

TypeError

A complex element (CPython's float() text).

ValueError

A text that is not a float literal.

explicit operator string(NDArray)

public static explicit operator string(NDArray d)

Parameters

d NDArray

Returns

string

explicit operator ushort(NDArray)

NumPy's int(arr) as a uint16, checked (see ToCheckedInteger<T>(NDArray, NPTypeCode)).

public static explicit operator ushort(NDArray nd)

Parameters

nd NDArray

A 0-d array.

Returns

ushort

The element as a ushort, exact.

Exceptions

TypeError

nd is not 0-d (only 0-dimensional arrays can be converted to Python scalars), or a complex element.

ValueError

A float NaN, or a text that is not an integer literal.

OverflowError

A float infinity, or a value outside uint16.

explicit operator uint(NDArray)

NumPy's int(arr) as a uint32, checked (see ToCheckedInteger<T>(NDArray, NPTypeCode)).

public static explicit operator uint(NDArray nd)

Parameters

nd NDArray

A 0-d array.

Returns

uint

The element as a uint, exact.

Exceptions

TypeError

nd is not 0-d (only 0-dimensional arrays can be converted to Python scalars), or a complex element.

ValueError

A float NaN, or a text that is not an integer literal.

OverflowError

A float infinity, or a value outside uint32.

explicit operator ulong(NDArray)

NumPy's int(arr) as a uint64, checked (see ToCheckedInteger<T>(NDArray, NPTypeCode)).

public static explicit operator ulong(NDArray nd)

Parameters

nd NDArray

A 0-d array.

Returns

ulong

The element as a ulong, exact.

Exceptions

TypeError

nd is not 0-d (only 0-dimensional arrays can be converted to Python scalars), or a complex element.

ValueError

A float NaN, or a text that is not an integer literal.

OverflowError

A float infinity, or a value outside uint64.

operator >(NDArray, NDArray)

Element-wise greater-than comparison (>). Supports all 12 dtypes and broadcasting.

public static NDArray<bool> operator >(NDArray lhs, NDArray rhs)

Parameters

lhs NDArray
rhs NDArray

Returns

NDArray<bool>

operator >(NDArray, object)

Element-wise greater-than comparison with scalar (>).

public static NDArray<bool> operator >(NDArray lhs, object rhs)

Parameters

lhs NDArray
rhs object

Returns

NDArray<bool>

operator >(NDArray, string)

Element-wise greater-than against a C# string (see the type remarks).

public static NDArray<bool> operator >(NDArray lhs, string rhs)

Parameters

lhs NDArray

The array.

rhs string

The string, or null.

Returns

NDArray<bool>

The bool result of lhs > rhs.

Exceptions

TypeError

An S array.

IncorrectShapeException

The legacy conversion of rhs does not broadcast.

operator >(object, NDArray)

Element-wise greater-than comparison with scalar on left (>).

public static NDArray<bool> operator >(object lhs, NDArray rhs)

Parameters

lhs object
rhs NDArray

Returns

NDArray<bool>

operator >(string, NDArray)

Element-wise greater-than of a C# string against an array: Python's reflection rhs < lhs (see the type remarks).

public static NDArray<bool> operator >(string lhs, NDArray rhs)

Parameters

lhs string

The string, or null.

rhs NDArray

The array.

Returns

NDArray<bool>

The bool result of lhs > rhs.

Exceptions

TypeError

An S array (NumPy's text names less, the reflected ufunc).

IncorrectShapeException

The legacy conversion of lhs does not broadcast.

operator >=(NDArray, NDArray)

Element-wise greater-than-or-equal comparison (>=). Supports all 12 dtypes and broadcasting.

public static NDArray<bool> operator >=(NDArray lhs, NDArray rhs)

Parameters

lhs NDArray
rhs NDArray

Returns

NDArray<bool>

operator >=(NDArray, object)

Element-wise greater-than-or-equal comparison with scalar (>=).

public static NDArray<bool> operator >=(NDArray lhs, object rhs)

Parameters

lhs NDArray
rhs object

Returns

NDArray<bool>

operator >=(NDArray, string)

Element-wise greater-or-equal against a C# string (see the type remarks).

public static NDArray<bool> operator >=(NDArray lhs, string rhs)

Parameters

lhs NDArray

The array.

rhs string

The string, or null.

Returns

NDArray<bool>

The bool result of lhs >= rhs.

Exceptions

TypeError

An S array.

IncorrectShapeException

The legacy conversion of rhs does not broadcast.

operator >=(object, NDArray)

Element-wise greater-than-or-equal comparison with scalar on left (>=).

public static NDArray<bool> operator >=(object lhs, NDArray rhs)

Parameters

lhs object
rhs NDArray

Returns

NDArray<bool>

operator >=(string, NDArray)

Element-wise greater-or-equal of a C# string against an array: Python's reflection rhs <= lhs (see the type remarks).

public static NDArray<bool> operator >=(string lhs, NDArray rhs)

Parameters

lhs string

The string, or null.

rhs NDArray

The array.

Returns

NDArray<bool>

The bool result of lhs >= rhs.

Exceptions

TypeError

An S array (NumPy's text names less_equal, the reflected ufunc).

IncorrectShapeException

The legacy conversion of lhs does not broadcast.

implicit operator NDArray(Array)

Converts a managed array (any rank, or jagged) into an NDArray copy of its data; a null array converts to a null NDArray. Text — a string array, or an object array holding strings / byte[] values — becomes NumPy's fixed-width string array (np.array(['a', 'bb']) is <U2), so NDArray x = new[] { "a", "bb" } and every NDArray parameter fed a C# string array (C# prefers the NDArray overload to an object one) read the text as NumPy does.

public static implicit operator NDArray(Array array)

Parameters

array Array

The array to convert, or null. An NDArray[] is NumPy's list of arrays and is stacked (np.asarray(new[] { a, b }) of two (3,) arrays is (2, 3)).

Returns

NDArray

A new array holding a copy of the elements, or null when array is null.

Remarks

C# runs a user-defined conversion even for a null source, so without the null pass-through an optional NDArray parameter fed from a null double[] variable (a common way to spell NumPy's p=None) crashed with a NullReferenceException instead of meaning "not given".

Exceptions

NotSupportedException

The element type is not one of NumSharp's dtypes.

ValueError

A ragged jagged array (text or numbers) or a list of arrays of unequal shapes (NumPy's inhomogeneous-shape text).

implicit operator NDArray(bool)

A 0-d bool array (not a Python-literal mark: NumPy stores a bool like its cast).

public static implicit operator NDArray(bool d)

Parameters

d bool

The value.

Returns

NDArray

implicit operator NDArray(byte)

A 0-d uint8 array marked as a Python int literal (see NumSharp.NDArray.WasPythonLiteral).

public static implicit operator NDArray(byte d)

Parameters

d byte

The value.

Returns

NDArray

implicit operator NDArray(char)

A 0-d char array marked as a NumPy uint16 scalar (see NumSharp.NDArray.WasNumPyScalar).

public static implicit operator NDArray(char d)

Parameters

d char

The value.

Returns

NDArray

implicit operator NDArray(decimal)

A 0-d decimal array (NumSharp-only, a NumPy-scalar-like value, not a Python-literal mark).

public static implicit operator NDArray(decimal d)

Parameters

d decimal

The value.

Returns

NDArray

implicit operator NDArray(double)

A 0-d float64 array marked as a Python float literal (see NumSharp.NDArray.WasPythonLiteral).

public static implicit operator NDArray(double d)

Parameters

d double

The value.

Returns

NDArray

implicit operator NDArray(Half)

A 0-d float16 array marked as a NumPy float16 scalar (see NumSharp.NDArray.WasNumPyScalar).

public static implicit operator NDArray(Half d)

Parameters

d Half

The value.

Returns

NDArray

implicit operator NDArray(short)

A 0-d int16 array marked as a Python int literal (see NumSharp.NDArray.WasPythonLiteral).

public static implicit operator NDArray(short d)

Parameters

d short

The value.

Returns

NDArray

implicit operator NDArray(int)

A 0-d int32 array marked as a Python int literal (see NumSharp.NDArray.WasPythonLiteral).

public static implicit operator NDArray(int d)

Parameters

d int

The value.

Returns

NDArray

implicit operator NDArray(long)

A 0-d int64 array marked as a Python int literal (see NumSharp.NDArray.WasPythonLiteral).

public static implicit operator NDArray(long d)

Parameters

d long

The value.

Returns

NDArray

implicit operator NDArray(Complex)

A 0-d complex128 array marked as a Python complex literal (see NumSharp.NDArray.WasPythonLiteral).

public static implicit operator NDArray(Complex d)

Parameters

d Complex

The value.

Returns

NDArray

implicit operator NDArray(sbyte)

A 0-d int8 array marked as a Python int literal (see NumSharp.NDArray.WasPythonLiteral).

public static implicit operator NDArray(sbyte d)

Parameters

d sbyte

The value.

Returns

NDArray

implicit operator NDArray(float)

A 0-d float32 array marked as a Python float literal (see NumSharp.NDArray.WasPythonLiteral).

public static implicit operator NDArray(float d)

Parameters

d float

The value.

Returns

NDArray

implicit operator NDArray(string)

A C# string is a Python str: the 0-d text array np.array(str) builds (<U{len}), marked as the Python str it stands for (NumSharp.NDArray.WasPythonStr), so a[i] = "xy" stores text into an S / U array and a[i] = "12" parses it into a numeric one with NumPy's setitem texts.

public static implicit operator NDArray(string str)

Parameters

str string

The text.

Returns

NDArray

The 0-d text array.

Remarks

A text shaped like "[1, 2, 3]" or "[1 2; 3 4]" stays text, because NumPy never reads a str as numbers in np.array (np.array('[1, 2, 3]') is the 0-d <U9 text). Breaking change: older NumSharp parsed such a text into a float64 vector or matrix here. Parse delimited numbers with np.fromstring; matrix(string, DType, bool) keeps its own literal grammar ("1 2; 3 4").

Exceptions

ArgumentNullException

str is null.

implicit operator NDArray(ushort)

A 0-d uint16 array marked as a Python int literal (see NumSharp.NDArray.WasPythonLiteral).

public static implicit operator NDArray(ushort d)

Parameters

d ushort

The value.

Returns

NDArray

implicit operator NDArray(uint)

A 0-d uint32 array marked as a Python int literal (see NumSharp.NDArray.WasPythonLiteral).

public static implicit operator NDArray(uint d)

Parameters

d uint

The value.

Returns

NDArray

implicit operator NDArray(ulong)

A 0-d uint64 array marked as a Python int literal (see NumSharp.NDArray.WasPythonLiteral).

public static implicit operator NDArray(ulong d)

Parameters

d ulong

The value.

Returns

NDArray

operator !=(NDArray, NDArray)

NumPy's a != b (array_richcompare): the elementwise not_equal ufunc over the broadcast operands, as a typed bool array — NOT a reference or value-inequality test. Where the ufunc has no loop for a string operand (text against numbers, two string classes that do not compare) the answer is True everywhere instead of an error, as NumPy's operator gives it.

public static NDArray<bool> operator !=(NDArray lhs, NDArray rhs)

Parameters

lhs NDArray

The left operand; null compares as C# null (see remarks).

rhs NDArray

The right operand; null compares as C# null.

Returns

NDArray<bool>

The bool comparison in the broadcast shape; a 0-d bool for a null operand; an empty bool array of lhs's shape when lhs is uninitialized (has no shape at all).

Remarks

Footgun: if (a != b) does not compile into an inequality test — the result is an array. Use !a.array_equal(b) (or np.any(a != b)) for one bool, and ReferenceEquals(object, object) for identity.

The null answers are C#'s protocol, not NumPy's: two nulls are a 0-d False, one null a 0-d True. They and the uninitialized-array answer stay here; the comparison itself is RichCompareEquality(NDArray, NDArray, bool), the engine's (the np-layer dtype plan, P1c).

Not scoped: the engine returns a bool-typed result that AsGeneric passes through, so this hot path mints no temporary to reclaim (see the == operator).

Exceptions

IncorrectShapeException

The operands do not broadcast (NumPy's ValueError text).

operator !=(NDArray, object)

Element-wise not-equal comparison with scalar (!=).

public static NDArray<bool> operator !=(NDArray lhs, object rhs)

Parameters

lhs NDArray
rhs object

Returns

NDArray<bool>

operator !=(NDArray, string)

Element-wise inequality with a C# string (see the type remarks).

public static NDArray<bool> operator !=(NDArray lhs, string rhs)

Parameters

lhs NDArray

The array.

rhs string

The string, or null.

Returns

NDArray<bool>

The bool result of lhs != rhs.

Exceptions

IncorrectShapeException

The legacy conversion of rhs does not broadcast.

operator !=(object, NDArray)

Element-wise not-equal comparison with scalar on left (!=).

public static NDArray<bool> operator !=(object lhs, NDArray rhs)

Parameters

lhs object
rhs NDArray

Returns

NDArray<bool>

operator !=(string, NDArray)

Element-wise inequality of a C# string with an array: Python's reflection rhs != lhs (see the type remarks).

public static NDArray<bool> operator !=(string lhs, NDArray rhs)

Parameters

lhs string

The string, or null.

rhs NDArray

The array.

Returns

NDArray<bool>

The bool result of lhs != rhs.

Exceptions

IncorrectShapeException

The legacy conversion of lhs does not broadcast.

operator <<(NDArray, NDArray)

Element-wise left shift. Integer dtypes only. Shifts bits of lhs left by rhs. Broadcast-aware.

public static NDArray operator <<(NDArray lhs, NDArray rhs)

Parameters

lhs NDArray
rhs NDArray

Returns

NDArray

operator <<(NDArray, object)

Element-wise left shift with any scalar or array-like on RHS. Converts RHS via OperatorOperand(object): a boxed C# number is the weak Python scalar NumPy's operator hands the ufunc, anything else np.asanyarray(rhs).

public static NDArray operator <<(NDArray lhs, object rhs)

Parameters

lhs NDArray
rhs object

Returns

NDArray

operator <(NDArray, NDArray)

Element-wise less-than comparison (<). Supports all 12 dtypes and broadcasting.

public static NDArray<bool> operator <(NDArray lhs, NDArray rhs)

Parameters

lhs NDArray
rhs NDArray

Returns

NDArray<bool>

operator <(NDArray, object)

Element-wise less-than comparison with scalar (<).

public static NDArray<bool> operator <(NDArray lhs, object rhs)

Parameters

lhs NDArray
rhs object

Returns

NDArray<bool>

operator <(NDArray, string)

Element-wise less-than against a C# string (see the type remarks).

public static NDArray<bool> operator <(NDArray lhs, string rhs)

Parameters

lhs NDArray

The array.

rhs string

The string, or null.

Returns

NDArray<bool>

The bool result of lhs < rhs.

Exceptions

TypeError

An S array (NumPy has no less loop for bytes against str).

IncorrectShapeException

The legacy conversion of rhs does not broadcast.

operator <(object, NDArray)

Element-wise less-than comparison with scalar on left (<).

public static NDArray<bool> operator <(object lhs, NDArray rhs)

Parameters

lhs object
rhs NDArray

Returns

NDArray<bool>

operator <(string, NDArray)

Element-wise less-than of a C# string against an array: Python's reflection rhs > lhs (see the type remarks).

public static NDArray<bool> operator <(string lhs, NDArray rhs)

Parameters

lhs string

The string, or null.

rhs NDArray

The array.

Returns

NDArray<bool>

The bool result of lhs < rhs.

Exceptions

TypeError

An S array (NumPy's text names greater, the reflected ufunc).

IncorrectShapeException

The legacy conversion of lhs does not broadcast.

operator <=(NDArray, NDArray)

Element-wise less-than-or-equal comparison (<=). Supports all 12 dtypes and broadcasting.

public static NDArray<bool> operator <=(NDArray lhs, NDArray rhs)

Parameters

lhs NDArray
rhs NDArray

Returns

NDArray<bool>

operator <=(NDArray, object)

Element-wise less-than-or-equal comparison with scalar (<=).

public static NDArray<bool> operator <=(NDArray lhs, object rhs)

Parameters

lhs NDArray
rhs object

Returns

NDArray<bool>

operator <=(NDArray, string)

Element-wise less-or-equal against a C# string (see the type remarks).

public static NDArray<bool> operator <=(NDArray lhs, string rhs)

Parameters

lhs NDArray

The array.

rhs string

The string, or null.

Returns

NDArray<bool>

The bool result of lhs <= rhs.

Exceptions

TypeError

An S array.

IncorrectShapeException

The legacy conversion of rhs does not broadcast.

operator <=(object, NDArray)

Element-wise less-than-or-equal comparison with scalar on left (<=).

public static NDArray<bool> operator <=(object lhs, NDArray rhs)

Parameters

lhs object
rhs NDArray

Returns

NDArray<bool>

operator <=(string, NDArray)

Element-wise less-or-equal of a C# string against an array: Python's reflection rhs >= lhs (see the type remarks).

public static NDArray<bool> operator <=(string lhs, NDArray rhs)

Parameters

lhs string

The string, or null.

rhs NDArray

The array.

Returns

NDArray<bool>

The bool result of lhs <= rhs.

Exceptions

TypeError

An S array (NumPy's text names greater_equal, the reflected ufunc).

IncorrectShapeException

The legacy conversion of lhs does not broadcast.

operator !(NDArray)

NumSharp's ! operator: NumPy's np.logical_not(a) as a typed bool array (Python has no !; this is its logical_not).

public static NDArray<bool> operator !(NDArray self)

Parameters

self NDArray

The operand (any dtype, any layout).

Returns

NDArray<bool>

The truth negation, an NDArray<TDType> of bool over np.logical_not's result.

Remarks

The whole call is np.logical_not's (the np-layer dtype plan, P1c): its text refusal, the bool route (invert) and the comparison with 0 for numbers (a NaN is true, -0.0 false). The operator held a raw scalar loop of its own for C-contiguous operands (x.Equals(default) per element, behind its own text guard), which the comparison kernels outrun: float64 at 100K elements took ~0.5 ms there.

Scope: MakeGeneric<bool>() mints a typed ALIAS over the result's storage (its own ARC ref); the untyped result wrapper would then be a strand reclaimable only by a future GC and finalizer pass (measured: one bucketed buffer escaped per !arr call). The [NDScoped] weaver tracks it, yields the alias and disposes the wrapper at exit. self is an input constructed before the scope opens, so it is never tracked.

Exceptions

TypeError

self holds text: logical_not has no string loop (NumPy's "ufunc 'logical_not' not supported for the input types, ..." text).

operator %(NDArray, NDArray)

public static NDArray operator %(NDArray x, NDArray y)

Parameters

x NDArray
y NDArray

Returns

NDArray

operator %(NDArray, object)

public static NDArray operator %(NDArray left, object right)

Parameters

left NDArray
right object

Returns

NDArray

operator %(object, NDArray)

public static NDArray operator %(object left, NDArray right)

Parameters

left object
right NDArray

Returns

NDArray

operator *(NDArray, NDArray)

public static NDArray operator *(NDArray x, NDArray y)

Parameters

x NDArray
y NDArray

Returns

NDArray

operator *(NDArray, object)

public static NDArray operator *(NDArray left, object right)

Parameters

left NDArray
right object

Returns

NDArray

operator *(NDArray, string)

Multiplication by a C# string (see the type remarks): for a string array, NumPy's no-loop TypeError.

public static NDArray operator *(NDArray lhs, string rhs)

Parameters

lhs NDArray

The array.

rhs string

The string, or null.

Returns

NDArray

The result of np.multiply(lhs, rhs) for a non-text array (the legacy conversion).

Exceptions

TypeError

A string array (NumPy has no loop for two strings).

IncorrectShapeException

The legacy conversion of rhs does not broadcast.

operator *(object, NDArray)

public static NDArray operator *(object left, NDArray right)

Parameters

left object
right NDArray

Returns

NDArray

operator *(string, NDArray)

Multiplication of a C# string by an array (see the type remarks): Python's rmul, the string first.

public static NDArray operator *(string lhs, NDArray rhs)

Parameters

lhs string

The string, or null.

rhs NDArray

The array.

Returns

NDArray

The result of np.multiply(lhs, rhs) for a non-text array (the legacy conversion).

Exceptions

TypeError

A string array.

IncorrectShapeException

The legacy conversion of lhs does not broadcast.

operator ~(NDArray)

Element-wise bitwise NOT (invert) operation. For boolean arrays: logical NOT (~True = False, ~False = True). For integer arrays: bitwise NOT (~0 = -1, ~1 = -2, etc.).

public static NDArray operator ~(NDArray x)

Parameters

x NDArray

Returns

NDArray

Remarks

Matches NumPy's ~ operator behavior:

  • Boolean: ~arr is equivalent to np.logical_not(arr)
  • Integer: ~arr is equivalent to np.invert(arr)

operator >>(NDArray, NDArray)

Element-wise right shift. Integer dtypes only. Shifts bits of lhs right by rhs. Logical shift for unsigned types, arithmetic shift for signed types. Broadcast-aware.

public static NDArray operator >>(NDArray lhs, NDArray rhs)

Parameters

lhs NDArray
rhs NDArray

Returns

NDArray

operator >>(NDArray, object)

Element-wise right shift with any scalar or array-like on RHS. Converts RHS via OperatorOperand(object): a boxed C# number is the weak Python scalar NumPy's operator hands the ufunc, anything else np.asanyarray(rhs).

public static NDArray operator >>(NDArray lhs, object rhs)

Parameters

lhs NDArray
rhs object

Returns

NDArray

operator -(NDArray, NDArray)

public static NDArray operator -(NDArray x, NDArray y)

Parameters

x NDArray
y NDArray

Returns

NDArray

operator -(NDArray, object)

public static NDArray operator -(NDArray left, object right)

Parameters

left NDArray
right object

Returns

NDArray

operator -(object, NDArray)

public static NDArray operator -(object left, NDArray right)

Parameters

left object
right NDArray

Returns

NDArray

operator -(NDArray)

public static NDArray operator -(NDArray x)

Parameters

x NDArray

Returns

NDArray

operator +(NDArray)

NumPy's unary +arr, the positive ufunc: a fresh copy of x in its own dtype.

public static NDArray operator +(NDArray x)

Parameters

x NDArray

The operand.

Returns

NDArray

A copy of x (never x itself, as NumPy's ufunc allocates its output), laid out as the ufunc allocates it (an F-ordered operand gives an F-ordered result).

Remarks

The whole call is the engine's Positive(NDArray, DType, NDArray, NDArray), as for np.positive (the np-layer dtype plan, P1c). The operator used to check text itself and return x.copy(): a bool operand was copied where NumPy raises, and an F-ordered one came back C-ordered.

Exceptions

TypeError

x is a bool array (positive has no bool loop: NumPy's ufunc 'positive' did not contain a loop with signature matching types <class 'numpy.dtypes.BoolDType'> -> None), or holds text (no string loop: the class-named text).