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)

Constructor which takes .NET array dtype and shape is determined from array

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

Parameters

values IArraySlice
shape Shape
order char

Remarks

This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type)

NDArray(UnmanagedStorage)

Creates a new NDArray with this storage.

public NDArray(UnmanagedStorage storage)

Parameters

storage UnmanagedStorage

NDArray(UnmanagedStorage, Shape)

Creates a new NDArray with this storage.

protected NDArray(UnmanagedStorage storage, Shape shape)

Parameters

storage UnmanagedStorage
shape Shape

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

Remarks

Doesn't copy. Does not perform checks for shape.

NDArray(UnmanagedStorage, ref Shape)

Creates a new NDArray with this storage.

protected NDArray(UnmanagedStorage storage, ref Shape shape)

Parameters

storage UnmanagedStorage
shape Shape

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

Remarks

Doesn't copy. Does not perform checks for shape.

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/>

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, 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)

Constructor which takes .NET array dtype and shape is determined from array

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

Parameters

values Array
shape Shape
order char

Remarks

This constructor calls IStorage.Allocate(NumSharp.Shape,System.Type)

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

Get: Gets internal storage array by calling IStorage.GetData
Set: Replace internal storage by calling IStorage.ReplaceData(System.Array)

protected IArraySlice Array { get; }

Property Value

IArraySlice

Remarks

Setting does not replace internal storage array.

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[NDArray<bool>]

Used to perform selection based on a boolean mask.

[SuppressMessage("ReSharper", "CoVariantArrayConversion")]
public NDArray this[NDArray<bool> mask] { get; set; }

Parameters

mask NDArray<bool>

Property Value

NDArray

Remarks

Exceptions

IndexOutOfRangeException

When one of the indices exceeds limits.

ArgumentException

indices must be of Int type (byte, u/short, u/int, u/long).

this[NDArray<int>[]]

Used to perform selection based on a selection indices.

public NDArray this[params NDArray<int>[] selection] { get; set; }

Parameters

selection NDArray<int>[]

Property Value

NDArray

Remarks

Exceptions

IndexOutOfRangeException

When one of the indices exceeds limits.

ArgumentException

indices must be of Int type (byte, u/short, u/int, u/long).

this[Slice[]]

Slice the array with Python slice notation like this: ":, 2:7:1, ..., np.newaxis"

public NDArray this[params Slice[] slice] { get; set; }

Parameters

slice Slice[]

A string containing slice notations for every dimension, delimited by comma

Property Value

NDArray

A sliced view

this[long*, int]

Used to perform selection based on given indices.

public NDArray this[long* dims, int ndims] { get; set; }

Parameters

dims long*

The pointer to the dimensions

ndims int

The count of longs in dims

Property Value

NDArray

this[object[]]

Perform slicing, index extraction, masking and indexing all at the same time with mixed index objects

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

Parameters

indicesObjects object[]

Property Value

NDArray

this[string]

Slice the array with Python slice notation like this: ":, 2:7:1, ..., np.newaxis"

public NDArray this[string slice] { get; set; }

Parameters

slice string

A string containing slice notations for every dimension, delimited by comma

Property Value

NDArray

A sliced view

Shape

The shape representing this NDArray.

public Shape Shape { get; set; }

Property Value

Shape

T

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

public NDArray T { get; }

Property Value

NDArray

Remarks

TensorEngine

The tensor engine that handles this NDArray.

public TensorEngine TensorEngine { get; set; }

Property Value

TensorEngine

Unsafe

Provides an interface for unsafe methods in NDArray.

public NDArray._Unsafe Unsafe { get; }

Property Value

NDArray._Unsafe

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

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

public int dtypesize { get; }

Property Value

int

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

public long[] shape { get; set; }

Property Value

long[]

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. Internal kernels that need ELEMENT strides must read Shape.View.Shape.Strides instead.

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 UnmanagedStorage.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.

AsStringArray(NDArray)

Convert to String[] from NDArray

public static string[] AsStringArray(NDArray arr)

Parameters

arr NDArray

Returns

string[]

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 (using Count).

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 (using Count).

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 (using Count).

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)

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

Parameters

src NDArray
indices NDArray[]
out NDArray
extraDim bool

Returns

NDArray

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

Accepts collapsed

[SuppressMessage("ReSharper", "SuggestVarOrType_Elsewhere")]
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>
indices NDArray[]
ndsCount int
retShape long[]
subShape long[]
out NDArray

Returns

NDArray<T>

Type Parameters

T

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

Accepts collapsed

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>
offsets NDArray<long>
indices NDArray[]
ndsCount int
retShape long[]
subShape long[]
out NDArray

Returns

NDArray<T>

Type Parameters

T

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

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

Parameters

source NDArray<T>
indices NDArray[]
out NDArray
extraDim bool

Returns

NDArray<T>

Type Parameters

T

~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 vector ndarray of bytes.

public static NDArray FromString(string str)

Parameters

str string

Returns

NDArray

GetAtIndex(long)

Retrieves value of

public object GetAtIndex(long index)

Parameters

index long

Returns

object

GetAtIndex<T>(long)

Retrieves value of

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

Parameters

index long

Returns

T

Type Parameters

T

GetBoolean(int[])

Retrieves value of type bool.

public bool GetBoolean(int[] indices)

Parameters

indices int[]

The shape's indices to get.

Returns

bool

Exceptions

NullReferenceException

When DType is not bool

GetBoolean(params long[])

public bool GetBoolean(params long[] indices)

Parameters

indices long[]

Returns

bool

GetByte(int[])

Retrieves value of type byte.

public byte GetByte(int[] indices)

Parameters

indices int[]

The shape's indices to get.

Returns

byte

Exceptions

NullReferenceException

When DType is not byte

GetByte(params long[])

public byte GetByte(params long[] indices)

Parameters

indices long[]

Returns

byte

GetChar(int[])

Retrieves value of type char.

public char GetChar(int[] indices)

Parameters

indices int[]

The shape's indices to get.

Returns

char

Exceptions

NullReferenceException

When DType is not char

GetChar(params long[])

public char GetChar(params long[] indices)

Parameters

indices long[]

Returns

char

GetComplex(int[])

public Complex GetComplex(int[] indices)

Parameters

indices int[]

Returns

Complex

GetComplex(params long[])

public Complex GetComplex(params long[] indices)

Parameters

indices long[]

Returns

Complex

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[])

Retrieves value of type decimal.

public decimal GetDecimal(int[] indices)

Parameters

indices int[]

The shape's indices to get.

Returns

decimal

Exceptions

NullReferenceException

When DType is not decimal

GetDecimal(params long[])

public decimal GetDecimal(params long[] indices)

Parameters

indices long[]

Returns

decimal

GetDouble(int[])

Retrieves value of type double.

public double GetDouble(int[] indices)

Parameters

indices int[]

The shape's indices to get.

Returns

double

Exceptions

NullReferenceException

When DType is not double

GetDouble(params long[])

public double GetDouble(params long[] indices)

Parameters

indices long[]

Returns

double

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
  • N-D arrays (N > 1): yields (N-1)-D NDArray slices along first axis

GetHalf(int[])

public Half GetHalf(int[] indices)

Parameters

indices int[]

Returns

Half

GetHalf(params long[])

public Half GetHalf(params long[] indices)

Parameters

indices long[]

Returns

Half

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[])

Used to perform selection based on indices, equivalent to nd[NDArray[]].

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

Parameters

out NDArray
indices NDArray[]

Returns

NDArray

Remarks

Exceptions

IndexOutOfRangeException

When one of the indices exceeds limits.

ArgumentException

indices must be of Int type (byte, u/short, u/int, u/long).

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[])

Retrieves value of type short.

public short GetInt16(int[] indices)

Parameters

indices int[]

The shape's indices to get.

Returns

short

Exceptions

NullReferenceException

When DType is not short

GetInt16(params long[])

public short GetInt16(params long[] indices)

Parameters

indices long[]

Returns

short

GetInt32(int[])

Retrieves value of type int.

public int GetInt32(int[] indices)

Parameters

indices int[]

The shape's indices to get.

Returns

int

Exceptions

NullReferenceException

When DType is not int

GetInt32(params long[])

public int GetInt32(params long[] indices)

Parameters

indices long[]

Returns

int

GetInt64(int[])

Retrieves value of type long.

public long GetInt64(int[] indices)

Parameters

indices int[]

The shape's indices to get.

Returns

long

Exceptions

NullReferenceException

When DType is not long

GetInt64(params long[])

public long GetInt64(params long[] indices)

Parameters

indices long[]

Returns

long

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[])

public sbyte GetSByte(int[] indices)

Parameters

indices int[]

Returns

sbyte

GetSByte(params long[])

public sbyte GetSByte(params long[] indices)

Parameters

indices long[]

Returns

sbyte

GetSingle(int[])

Retrieves value of type float.

public float GetSingle(int[] indices)

Parameters

indices int[]

The shape's indices to get.

Returns

float

Exceptions

NullReferenceException

When DType is not float

GetSingle(params long[])

public float GetSingle(params long[] indices)

Parameters

indices long[]

Returns

float

GetString(params long[])

Get a string out of a vector of chars.

public string GetString(params long[] indices)

Parameters

indices long[]

Returns

string

Remarks

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

GetStringAt(long)

Get a string out of a vector of chars.

public string GetStringAt(long offset)

Parameters

offset long

Returns

string

Remarks

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

GetUInt16(int[])

Retrieves value of type ushort.

public ushort GetUInt16(int[] indices)

Parameters

indices int[]

The shape's indices to get.

Returns

ushort

Exceptions

NullReferenceException

When DType is not ushort

GetUInt16(params long[])

public ushort GetUInt16(params long[] indices)

Parameters

indices long[]

Returns

ushort

GetUInt32(int[])

Retrieves value of type uint.

public uint GetUInt32(int[] indices)

Parameters

indices int[]

The shape's indices to get.

Returns

uint

Exceptions

NullReferenceException

When DType is not uint

GetUInt32(params long[])

public uint GetUInt32(params long[] indices)

Parameters

indices long[]

Returns

uint

GetUInt64(int[])

Retrieves value of type ulong.

public ulong GetUInt64(int[] indices)

Parameters

indices int[]

The shape's indices to get.

Returns

ulong

Exceptions

NullReferenceException

When DType is not ulong

GetUInt64(params long[])

public ulong GetUInt64(params long[] indices)

Parameters

indices long[]

Returns

ulong

GetValue(int[])

Retrieves value of unspecified type (will figure using DType).

public object GetValue(int[] indices)

Parameters

indices int[]

The shape's indices to get.

Returns

object

Exceptions

NullReferenceException

When DType is not object

GetValue(params long[])

Retrieves value of unspecified type (will figure using DType).

public object GetValue(params long[] indices)

Parameters

indices long[]

The shape's indices to get.

Returns

object

Exceptions

NullReferenceException

When DType is not object

GetValue<T>(int[])

Retrieves value of unspecified type (will figure using DType).

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

Parameters

indices int[]

The shape's indices to get.

Returns

T

Type Parameters

T

Exceptions

NullReferenceException

When DType is not object

GetValue<T>(params long[])

Get a single value from NDArray as type T.

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

Parameters

indices long[]

The shape's indices to get.

Returns

T

Type Parameters

T

Exceptions

NullReferenceException

When DType is not object

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 UnmanagedStorage.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

Normalize()

Normalizes all entries into the range between 0 and 1

Note: this is not a numpy function.

[Obsolete("Non numpy functionality, will be removed in future versions. use np.clip() instead.")]
public void Normalize()

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) 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).

Exceptions

IndexOutOfRangeException

When the index array is not an integer type.

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>[]

ReplaceData(IArraySlice)

Sets values as the internal data source and changes the internal storage data type to values type.

public void ReplaceData(IArraySlice values)

Parameters

values IArraySlice

Remarks

Does not copy values and doesn't change shape.

ReplaceData(IArraySlice, Type)

Sets values as the internal data source and changes the internal storage data type to values type.

public void ReplaceData(IArraySlice values, Type dtype)

Parameters

values IArraySlice
dtype Type

Remarks

Does not copy values and doesn't change shape.

ReplaceData(NDArray)

Sets nd as the internal data storage and changes the internal storage data type to nd type.

public void ReplaceData(NDArray nd)

Parameters

nd NDArray

Remarks

Does not copy values and does change shape and dtype.

ReplaceData(Array)

Sets values as the internal data storage and changes the internal storage data type to values type.

public void ReplaceData(Array values)

Parameters

values Array

Remarks

Does not copy values.

ReplaceData(Array, NPTypeCode)

Set an Array to internal storage, cast it to new dtype and if necessary change dtype

public void ReplaceData(Array values, NPTypeCode typeCode)

Parameters

values Array
typeCode NPTypeCode

Remarks

Does not copy values unless cast is necessary and doesn't change shape.

ReplaceData(Array, Type)

Sets values as the internal data storage and changes the internal storage data type to dtype and casts values if necessary.

public void ReplaceData(Array values, Type dtype)

Parameters

values Array

The values to set as internal data soruce

dtype Type

The type to change this storage to and the type to cast values if necessary.

Remarks

Does not copy values unless cast is necessary.

Scalar(object)

Creates a scalar NDArray of value and dtype.

public static NDArray Scalar(object value)

Parameters

value object

The value of the scalar

Returns

NDArray

Remarks

In case when value is not dtype, Converts.ChangeType(object,System.Type) will be called.

Scalar(object, DType)

Creates a scalar NDArray of value and dtype.

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

Remarks

In case when value is not dtype, Converts.ChangeType(object,System.Type) will be called.

Scalar<T>(object)

Creates a scalar NDArray of value and dtype.

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

Parameters

value object

The value of the scalar, attempt to convert will be performed

Returns

NDArray

Type Parameters

T

Remarks

In case when value is not dtype, Converts.ChangeType(object,System.Type) will be called.

Scalar<T>(T)

Creates a scalar NDArray of value and dtype.

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

Parameters

value T

The value of the scalar

Returns

NDArray

Type Parameters

T

Remarks

In case when value is not dtype, Converts.ChangeType(object,System.Type) will be called.

SetAtIndex(object, long)

Retrieves value at given linear (offset) index.

public void SetAtIndex(object obj, long index)

Parameters

obj object
index long

SetAtIndex<T>(T, long)

Retrieves value of

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

Parameters

value T
index long

Type Parameters

T

SetBoolean(bool, int[])

Sets a bool at specific coordinates.

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

Parameters

value bool

The values to assign

indices int[]

The coordinates to set value at.

SetBoolean(bool, params long[])

Sets a bool at specific coordinates.

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

Parameters

value bool

The value to assign

indices long[]

The coordinates to set value at.

SetByte(byte, int[])

Sets a byte at specific coordinates.

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

Parameters

value byte

The values to assign

indices int[]

The coordinates to set value at.

SetByte(byte, params long[])

Sets a byte at specific coordinates.

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

Parameters

value byte

The value to assign

indices long[]

The coordinates to set value at.

SetChar(char, int[])

Sets a char at specific coordinates.

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

Parameters

value char

The values to assign

indices int[]

The coordinates to set value at.

SetChar(char, params long[])

Sets a char at specific coordinates.

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

Parameters

value char

The value to assign

indices long[]

The coordinates to set value at.

SetComplex(Complex, int[])

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

Parameters

value Complex
indices int[]

SetComplex(Complex, params long[])

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

Parameters

value Complex
indices long[]

SetData(IArraySlice, int[])

Set a IArraySlice at given indices.

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 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[])

Set a NDArray at given indices.

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 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.

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[])

Sets a decimal at specific coordinates.

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

Parameters

value decimal

The values to assign

indices int[]

The coordinates to set value at.

SetDecimal(decimal, params long[])

Sets a decimal at specific coordinates.

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

Parameters

value decimal

The value to assign

indices long[]

The coordinates to set value at.

SetDouble(double, int[])

Sets a double at specific coordinates.

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

Parameters

value double

The values to assign

indices int[]

The coordinates to set value at.

SetDouble(double, params long[])

Sets a double at specific coordinates.

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

Parameters

value double

The values to assign

indices long[]

The coordinates to set value at.

SetHalf(Half, int[])

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

Parameters

value Half
indices int[]

SetHalf(Half, params long[])

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

Parameters

value Half
indices long[]

SetIndices(NDArray, NDArray[])

Used to perform set a selection based on indices, equivalent to nd[NDArray[]] = values.

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

Parameters

values NDArray

The values to set via .

indices NDArray[]

Remarks

Exceptions

IndexOutOfRangeException

When one of the indices exceeds limits.

ArgumentException

indices must be of Int type (byte, u/short, u/int, u/long).

NumSharpException

If this array is not writeable (e.g., broadcast array).

SetIndices(NDArray, NDArray[], NDArray)

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

Parameters

src NDArray
indices NDArray[]
values NDArray

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 (SetIndicesND<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 FetchIndicesNDNonLinear: 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.

[SuppressMessage("ReSharper", "SuggestVarOrType_Elsewhere")]
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

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

Accepts collapsed

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>
dstOffsets NDArray<long>
dstIndices NDArray[]
ndsCount int
retShape long[]
subShape long[]
values NDArray<T>

Type Parameters

T

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

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

Parameters

source NDArray<T>
indices NDArray[]
values NDArray

Type Parameters

T

SetInt16(short, int[])

Sets a short at specific coordinates.

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

Parameters

value short

The values to assign

indices int[]

The coordinates to set value at.

SetInt16(short, params long[])

Sets a short at specific coordinates.

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

Parameters

value short

The value to assign

indices long[]

The coordinates to set value at.

SetInt32(int, int[])

Sets a int at specific coordinates.

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

Parameters

value int

The values to assign

indices int[]

The coordinates to set value at.

SetInt32(int, params long[])

Sets a int at specific coordinates.

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

Parameters

value int

The values to assign

indices long[]

The coordinates to set value at (long version).

SetInt64(long, int[])

Sets a long at specific coordinates.

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

Parameters

value long

The values to assign

indices int[]

The coordinates to set value at.

SetInt64(long, params long[])

Sets a long at specific coordinates.

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

Parameters

value long

The values to assign

indices long[]

The coordinates to set value at (long version).

SetSByte(sbyte, int[])

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

Parameters

value sbyte
indices int[]

SetSByte(sbyte, params long[])

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

Parameters

value sbyte
indices long[]

SetSingle(float, int[])

Sets a float at specific coordinates.

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

Parameters

value float

The values to assign

indices int[]

The coordinates to set value at.

SetSingle(float, params long[])

Sets a float at specific coordinates.

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

Parameters

value float

The value to assign

indices long[]

The coordinates to set value at.

SetString(string, params long[])

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

Parameters

value string
indices long[]

SetStringAt(string, long)

public void SetStringAt(string value, long offset)

Parameters

value string
offset long

SetUInt16(ushort, int[])

Sets a ushort at specific coordinates.

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

Parameters

value ushort

The values to assign

indices int[]

The coordinates to set value at.

SetUInt16(ushort, params long[])

Sets a ushort at specific coordinates.

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

Parameters

value ushort

The value to assign

indices long[]

The coordinates to set value at.

SetUInt32(uint, int[])

Sets a uint at specific coordinates.

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

Parameters

value uint

The values to assign

indices int[]

The coordinates to set value at.

SetUInt32(uint, params long[])

Sets a uint at specific coordinates.

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

Parameters

value uint

The value to assign

indices long[]

The coordinates to set value at.

SetUInt64(ulong, int[])

Sets a ulong at specific coordinates.

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

Parameters

value ulong

The values to assign

indices int[]

The coordinates to set value at.

SetUInt64(ulong, params long[])

Sets a ulong at specific coordinates.

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

Parameters

value ulong

The value to assign

indices long[]

The coordinates to set value at.

SetValue(object, int[])

Set a single value at given indices.

public void SetValue(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.

SetValue(object, params long[])

Set a single value at given indices.

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

Parameters

value object

The value to set

indices long[]

The coordinates (long version).

Remarks

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

SetValue<T>(T, int[])

Set a single value at given indices.

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

Parameters

value T

The value to set

indices int[]

The

Type Parameters

T

Remarks

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

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

Set a single value at given indices.

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

Parameters

value T

The value to set

indices long[]

The coordinates (long version).

Type Parameters

T

Remarks

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

ToArray<T>()

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

Returns

T[]

Type Parameters

T

ToJaggedArray<T>()

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

Returns

Array

Type Parameters

T

ToMuliDimArray<T>()

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

Returns

Array

Type Parameters

T

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

__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__(int)

Python-compatible getitem method with integer index.

public NDArray __getitem__(int index)

Parameters

index int

Index along the first axis.

Returns

NDArray

Element or slice at the given index.

Remarks

Equivalent to arr[index] in Python. Supports negative indexing (-1 = last element).

__getitem__(params int[])

Python-compatible getitem method with params indices.

public NDArray __getitem__(params int[] indices)

Parameters

indices int[]

Indices for each dimension.

Returns

NDArray

Element or slice at the given indices.

Remarks

A comma-separated index list is Python's basic (coordinate) indexing — arr[1, 2] selects the element at (1,2), arr[1] the sub-array along axis 0 — so it resolves through GetData(int[]). (A raw int[] passed to the this[...] indexer is now FANCY indexing for NumPy parity; fancy/list indexing is reached through the array/NDArray overloads instead.)

__getitem__(long)

Python-compatible getitem method with long index.

public NDArray __getitem__(long index)

Parameters

index long

Index along the first axis.

Returns

NDArray

Element or slice at the given index.

__getitem__(string)

Python-compatible getitem method with slice string.

public NDArray __getitem__(string slice)

Parameters

slice string

Slice specification (e.g., "1:3", "::-1", "..., 0").

Returns

NDArray

Sliced view of the array.

Remarks

Equivalent to arr[slice] in Python. Examples:

arr.__getitem__(":3")      // First 3 elements
arr.__getitem__("1:-1")    // All but first and last
arr.__getitem__("::-1")    // Reversed
arr.__getitem__("..., 0")  // All rows, first column

__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. NumSharp returns 1 for consistency with C# conventions. Use size for total element count.

__setitem__(int, object)

Python-compatible setitem method with integer index.

public void __setitem__(int index, object value)

Parameters

index int

Index along the first axis.

value object

Value to set (scalar or NDArray).

__setitem__(long, object)

Python-compatible setitem method with long index.

public void __setitem__(long index, object value)

Parameters

index long

Index along the first axis.

value object

Value to set (scalar or NDArray).

__setitem__(string, object)

Python-compatible setitem method with slice string.

public void __setitem__(string slice, object value)

Parameters

slice string

Slice specification.

value object

Value to set (scalar or NDArray).

all(int?, NDArray, bool, NDArray)

Returns True if all elements evaluate to True. Refer to all(NDArray, int?, NDArray, bool, NDArray) for full documentation.

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

Parameters

axis int?

Axis or axes along which a logical AND reduction is performed. The default (null) is to reduce over the flattened array.

out NDArray

Alternate output array in which to place the result. It must have the same shape as the expected output.

keepdims bool

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

where NDArray

Elements to include in the reduction (null means include all).

Returns

NDArray

Remarks

amax(DType)

Return the maximum of an array or maximum along an axis.

[SuppressMessage("ReSharper", "TooWideLocalVariableScope")]
[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray amax(DType dtype = null)

Parameters

dtype DType

the type expected as a return, null will remain the same dtype.

Returns

NDArray

Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Remarks

amax(int, bool, DType)

Return the maximum of an array or maximum along an axis.

[SuppressMessage("ReSharper", "TooWideLocalVariableScope")]
[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray amax(int axis, bool keepdims = false, DType dtype = null)

Parameters

axis int

Axis or axes along which to operate.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

dtype DType

the type expected as a return, null will remain the same dtype.

Returns

NDArray

Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Remarks

amax<T>()

Return the maximum of an array or maximum along an axis.

public T amax<T>() where T : unmanaged

Returns

T

Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Type Parameters

T

The expected return type, cast will be performed if necessary.

Remarks

amin(DType)

Return the minimum of an array or minimum along an axis.

[SuppressMessage("ReSharper", "TooWideLocalVariableScope")]
[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray amin(DType dtype = null)

Parameters

dtype DType

the type expected as a return, null will remain the same dtype.

Returns

NDArray

Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Remarks

amin(int, bool, DType)

Return the minimum of an array or minimum along an axis.

[SuppressMessage("ReSharper", "TooWideLocalVariableScope")]
[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray amin(int axis, bool keepdims = false, DType dtype = null)

Parameters

axis int

Axis or axes along which to operate.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

dtype DType

the type expected as a return, null will remain the same dtype.

Returns

NDArray

Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Remarks

amin<T>()

Return the minimum of an array or minimum along an axis.

public T amin<T>() where T : unmanaged

Returns

T

Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Type Parameters

T

The expected return type, cast will be performed if necessary.

Remarks

any(int?, NDArray, bool, NDArray)

Returns True if any of the elements of a evaluate to True. Refer to any(NDArray, int?, NDArray, bool, NDArray) for full documentation.

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

Parameters

axis int?

Axis or axes along which a logical OR reduction is performed. The default (null) is to reduce over the flattened array.

out NDArray

Alternate output array in which to place the result. It must have the same shape as the expected output.

keepdims bool

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

where NDArray

Elements to include in the reduction (null means include all).

Returns

NDArray

Remarks

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(int, bool)

Returns the indices of the maximum values along an axis.

public NDArray argmax(int axis, bool keepdims = false)

Parameters

axis int

The axis along which to operate. By default, the index is into the flattened array.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one.

Returns

NDArray

Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed (unless keepdims is True).

Remarks

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(int, bool)

Returns the indices of the minimum values along an axis.

public NDArray argmin(int axis, bool keepdims = false)

Parameters

axis int

The axis along which to operate. By default, the index is into the flattened array.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one.

Returns

NDArray

Array of indices into the array. It has the same shape as a.shape with the dimension along axis removed (unless keepdims is True).

Remarks

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?)

Returns the indices that would sort this array along axis (null flattens). NumPy np.argsort.

public NDArray argsort(int? axis = -1)

Parameters

axis int?

Returns

NDArray

argsort<T>(int)

Returns the indices that would sort an array along the given axis.

Indirect sort: returns an int64 array of the same shape whose values index this array along axis in sorted order (NumPy np.argsort). Stable (ties resolve in ascending index order). Floating NaN sorts to the end.

public NDArray argsort<T>(int axis = -1) where T : unmanaged

Parameters

axis int

Returns

NDArray

Type Parameters

T

Remarks

Implementation: NDIter drives the all-but-axis loop; each 1-D line is argsorted by a stable LSD radix kernel (NumSharp.Backends.Sorting.AxisSort). The generic parameter is retained for source compatibility — the element type is taken from the array's own dtype.

array_equal(NDArray)

True if two arrays have the same shape and elements, False otherwise.

public bool array_equal(NDArray rhs)

Parameters

rhs NDArray

Input array.

Returns

bool

Returns True if the arrays are equal.

Remarks

astype(DType, bool)

Copy of the array, cast to a specified type.

[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray astype(DType dtype, 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.

copy bool

By default, astype always returns a newly allocated array. If this is set to false and the dtype 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.

Remarks

astype(DType, bool, char, string)

Copy of the array, cast to a specified type and memory layout.

[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray astype(DType dtype, bool copy, char order, string casting = "unsafe")

Parameters

dtype DType

The dtype to cast this array to — one descriptor parameter, like NumPy's dtype: a C# Type, an NPTypeCode, a NumPy dtype string or a DType all convert implicitly.

copy bool

By default, astype always returns a newly allocated array. If this is set to false and the dtype 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).

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'). 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.

Returns

NDArray

An NDArray of given dtype with the requested layout.

Remarks

Exceptions

ArgumentNullException

dtype is null.

NotSupportedException

The descriptor's class has no storage lane yet (a datetime64/timedelta64 descriptor before Stage C).

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

Exceptions

ValueError

When inplace is true and the array is not writeable (e.g. a broadcast view).

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)

Return an array whose values are limited to [min, max]. If neither min nor max is given the array is returned unchanged (a copy). Refer to clip(NDArray, NDArray, NDArray, NDArray, DType, NDArray, NDArray) for full documentation.

public NDArray clip(NDArray min = null, NDArray max = null, NDArray @out = null, DType dtype = null)

Parameters

min NDArray

Minimum value. If null, clipping is not performed on the lower interval edge.

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. It may be the input array for in-place clipping.

dtype DType

The dtype the returned array should be of (NumPy's ndarray.clip(..., **kwargs) passes dtype through to the ufunc). Null (default) keeps the promoted result dtype.

Returns

NDArray

An array with the elements of this array, but where values < min are replaced with min, and those > max with max.

Remarks

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 np.conjugate(NDArray, NDArray, NDArray, NPTypeCode?) 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

Remarks

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): it reverses the kernel and runs the shared sliding multiply-accumulate engine (SlidingCorrelate(NDArray, NDArray, NPTypeCode, SlidingMode)). Unlike correlate it does NOT conjugate a complex kernel and is commutative, so the "swap if v longer" below needs no output reversal. See np.correlate.cs for the float bit-parity notes (both share the same kernel).

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 second argument is complex-conjugated first (real inputs unchanged); the shared engine (SlidingCorrelate(NDArray, NDArray, NPTypeCode, SlidingMode)) then swaps the operands when len(a) < len(v) — correlate is NOT commutative — and the output is reversed in that case (_pyarray_revert). The engine reads the kernel forward. Float bit-parity notes are in np.correlate.cs.

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)

Dot product of two arrays. See remarks.

public NDArray dot(NDArray b)

Parameters

b NDArray

Rhs, Second argument.

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])

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 an np.int64 scalar); a higher-rank array is a sequence and raises ValueError("setting an array element with a sequence.").

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).

Remarks

Exceptions

ArgumentNullException

value is null (NumSharp house convention, as in fill_diagonal(NDArray, object, bool); NumPy instead yields NaN for a float array / TypeError otherwise).

NumSharpException

This array is read-only (broadcast view / read-only memmap); NumPy raises ValueError: assignment destination is read-only.

OverflowException

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.

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' - memory order (reads the elements in the order they occur in memory).

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.

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.

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

ArgumentNullException

dtype is null.

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.

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>

Type Parameters

T

The field dtype (its itemsize must be ≤ this array's itemsize).

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

IncorrectSizeException

If array size is not 1.

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

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

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

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

IncorrectSizeException

If array size is not 1.

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.

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.

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.

itemset(Shape, object)

Insert scalar into an array (scalar is cast to array’s dtype, if possible)

public void itemset(Shape shape, object val)

Parameters

shape Shape
val object

Remarks

itemset(ref Shape, object)

Insert scalar into an array (scalar is cast to array’s dtype, if possible)

public void itemset(ref Shape shape, object val)

Parameters

shape Shape
val object

Remarks

itemset(int[], object)

Insert scalar into an array (scalar is cast to array’s dtype, if possible)

public void itemset(int[] shape, object val)

Parameters

shape int[]
val object

Remarks

itemset<T>(int[], T)

Insert scalar into an array (scalar is cast to array’s dtype, if possible)

public void itemset<T>(int[] shape, T val) where T : unmanaged

Parameters

shape int[]
val T

Type Parameters

T

Remarks

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(DType)

Return the maximum of an array or maximum along an axis.

[SuppressMessage("ReSharper", "TooWideLocalVariableScope")]
[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray max(DType dtype = null)

Parameters

dtype DType

the type expected as a return, null will remain the same dtype.

Returns

NDArray

Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Remarks

max(int, bool, DType)

Return the maximum of an array or maximum along an axis.

[SuppressMessage("ReSharper", "TooWideLocalVariableScope")]
[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray max(int axis, bool keepdims = false, DType dtype = null)

Parameters

axis int

Axis or axes along which to operate.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

dtype DType

the type expected as a return, null will remain the same dtype.

Returns

NDArray

Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Remarks

max<T>()

Return the maximum of an array or maximum along an axis.

public T max<T>() where T : unmanaged

Returns

T

Maximum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Type Parameters

T

The expected return type, cast will be performed if necessary.

Remarks

mean()

Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.

public NDArray mean()

Returns

NDArray

returns a new array containing the mean values, otherwise a reference to the output array is returned.

Remarks

mean(int)

Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.

public NDArray mean(int axis)

Parameters

axis int

Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.

Returns

NDArray

returns a new array containing the mean values, otherwise a reference to the output array is returned.

Remarks

mean(int, DType, bool)

Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.

public NDArray mean(int axis, DType dtype, bool keepdims = false)

Parameters

axis int

Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.

dtype DType
keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised.

Returns

NDArray

returns a new array containing the mean values, otherwise a reference to the output array is returned.

Remarks

mean(int, bool)

Compute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.

public NDArray mean(int axis, bool keepdims)

Parameters

axis int

Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the mean method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised.

Returns

NDArray

returns a new array containing the mean values, otherwise a reference to the output array is returned.

min(DType)

Return the minimum of an array or minimum along an axis.

[SuppressMessage("ReSharper", "TooWideLocalVariableScope")]
[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray min(DType dtype = null)

Parameters

dtype DType

the type expected as a return, null will remain the same dtype.

Returns

NDArray

Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Remarks

min(int, bool, DType)

Return the minimum of an array or minimum along an axis.

[SuppressMessage("ReSharper", "TooWideLocalVariableScope")]
[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray min(int axis, bool keepdims = false, DType dtype = null)

Parameters

axis int

Axis or axes along which to operate.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

dtype DType

the type expected as a return, null will remain the same dtype.

Returns

NDArray

Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Remarks

min<T>()

Return the minimum of an array or minimum along an axis.

public T min<T>() where T : unmanaged

Returns

T

Minimum of a. If axis is None, the result is a scalar value. If axis is given, the result is an array of dimension a.ndim - 1.

Type Parameters

T

The expected return type, cast will be performed if necessary.

Remarks

negate()

Negates all values by performing: -x

public NDArray negate()

Returns

NDArray

negative()

Numerical negative, element-wise. Returns -x for each element (negates ALL values, not just positive).

public NDArray negative()

Returns

NDArray

Remarks

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. This is an identity operation - returns +x (a copy of the input). Equivalent to np.array(a, copy=True).

public NDArray positive()

Returns

NDArray

Remarks

prod(int?, DType, bool)

Return the product of array elements over a given axis.

public NDArray prod(int? axis = null, DType dtype = null, bool keepdims = false)

Parameters

axis int?

Axis or axes along which a product is performed. The default, axis=None, will calculate the product of all the elements in the input array. If axis is negative it counts from the last to the first axis.

dtype DType

The type of the returned array, as well as of the accumulator in which the elements are multiplied. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

Returns

NDArray

An array shaped as a but with the specified axis removed.

Remarks

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()

Return a contiguous flattened array. A 1-D array, containing the elements of the input, is returned

public NDArray ravel()

Returns

NDArray

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)

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

Remarks

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

repeat(int, int?)

Repeat each element of the array after itself. Refer to repeat(NDArray, int, int?) for full documentation.

public NDArray repeat(int repeats, int? axis = null)

Parameters

repeats int

The number of repetitions for each element.

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

repeat(long, int?)

Repeat each element of the array after itself. Refer to repeat(NDArray, int, int?) for full documentation.

public NDArray repeat(long repeats, int? axis = null)

Parameters

repeats long

The number of repetitions for each element.

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

reshape(Shape)

Gives a new shape to an array without changing its data.

public NDArray reshape(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(Shape, char)

Gives a new shape to an array without changing its data, reading the elements in the specified index order.

public NDArray reshape(Shape newShape, char order)

Parameters

newShape Shape

The new shape (one dimension may be -1 — inferred, any order).

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").

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

reshape(ref Shape)

Gives a new shape to an array without changing its data.

public NDArray reshape(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(int[])

Gives a new shape to an array without changing its data.

[SuppressMessage("ReSharper", "ParameterHidesMember")]
public NDArray reshape(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(params long[])

Gives a new shape to an array without changing its data.

[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

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

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.

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 np.around(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).

dtype DType

The dtype of the field being set (its itemsize must be ≤ this array's itemsize).

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

ArgumentNullException

dtype or value is null.

ValueError

assignment destination is read-only (this array is not writeable), or one of getfield's three dtype/offset ValueErrors.

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. NumPy's "cannot set aligned flag of mis-aligned array to True" is unreachable here: NumSharp addresses memory in whole elements (element strides and offsets), so data can never sit mis-aligned for its own dtype — True always succeeds. Fresh views and copies of an align-cleared array come back ALIGNED, 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 NumSharp.Backends.UnmanagedStorage.WriteProtected on the boundary storage itself).

https://numpy.org/doc/stable/reference/generated/numpy.ndarray.setflags.html

Exceptions

ValueError

uic: true, or write: true on an array NumPy's rule refuses (see above).

sort(int?, string)

Sort this array in place along axis (default last; null flattens). NumPy ndarray.sort.

public void sort(int? axis = -1, string kind = null)

Parameters

axis int?
kind string

squeeze(int?)

Remove axes of length one from this array. Refer to squeeze(NDArray) for full documentation.

public NDArray squeeze(int? axis = null)

Parameters

axis int?

Selects a subset of the entries of length one to remove. The default (null) removes all length-one axes. 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

std(bool, int?, DType)

Compute the standard deviation along the specified axis. Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

public NDArray std(bool keepdims = false, int? ddof = null, DType dtype = null)

Parameters

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

ddof int?

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

dtype DType

Returns

NDArray

returns a new array containing the std values, otherwise a reference to the output array is returned.

Remarks

std(int, bool, int?, DType)

Compute the standard deviation along the specified axis. Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

public NDArray std(int axis, bool keepdims = false, int? ddof = null, DType dtype = null)

Parameters

axis int

Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

ddof int?

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

dtype DType

Returns

NDArray

returns a new array containing the std values, otherwise a reference to the output array is returned.

Remarks

sum()

Sum of array elements into a scalar.

public NDArray sum()

Returns

NDArray

An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

Remarks

sum(int)

Sum of array elements over a given axis.

public NDArray sum(int axis)

Parameters

axis int

Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.

Returns

NDArray

An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

Remarks

sum(int, bool, DType)

Sum of array elements over a given axis.

public NDArray sum(int axis, bool keepdims, DType dtype = null)

Parameters

axis int

Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input array. If axis is negative it counts from the last to the first axis.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array. If the default value is passed, then keepdims will not be passed through to the sum method of sub-classes of ndarray, however any non-default value will be.If the sub-class’ method does not implement keepdims any exceptions will be raised.

dtype DType

The type of the returned array and of the accumulator in which the elements are summed — one descriptor parameter, like NumPy's dtype: a C# Type, an NPTypeCode, a NumPy dtype string or a DType all convert implicitly. The dtype of a is used by default unless a has an integer dtype of less precision than the default platform integer. In that case, if a is signed then the platform integer is used while if a is unsigned then an unsigned integer of the same precision as the platform integer is used.

Returns

NDArray

An array with the same shape as a, with the specified axis removed. If a is a 0-d array, or if axis is None, a scalar is returned. If an output array is specified, a reference to out is returned.

Remarks

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 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

take(long, int?, NDArray, string)

Return the element (or sub-array) at a single index taken along an axis. Refer to take(NDArray, long, int?, NDArray, string) for full documentation.

public NDArray take(long index, int? axis = null, NDArray @out = null, string mode = "raise")

Parameters

index long

A single index of the value to extract.

axis int?

The axis over which to select the value. The default (null) works over the flattened array.

out NDArray

Optional output array of the right shape to hold the result.

mode string

How an out-of-bounds index behaves: "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).

ArgumentException

If device is not "cpu", or stream is non-null.

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

ArgumentException

Thrown when order is not one of C/F/A/K.

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.

format string

Python-style % format for text output (default "%s").

Remarks

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 np.fromfile(string,System.Type).

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')).

format string

Python-style % format string for text output (ignored in binary mode). Each entry is written as format % item. The default "%s" uses the element's NumPy scalar string (e.g. 1.5, (1+2j), True).

Remarks

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.

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(int[])

Permute the dimensions of an array.

public NDArray transpose(int[] premute = null)

Parameters

premute int[]

By default, reverse the dimensions, otherwise permute the axes according to the values given.

Returns

NDArray

a with its axes permuted. A view is returned whenever possible.

Remarks

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 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?].

Remarks

unique(int?, bool, bool)

public NDArray unique(int? axis = null, bool equal_nan = true, bool sorted = true)

Parameters

axis int?
equal_nan bool
sorted bool

Returns

NDArray

unique<T>()

protected NDArray unique<T>() where T : unmanaged, IComparable<T>

Returns

NDArray

Type Parameters

T

var(bool, int?, DType)

Compute the standard deviation along the specified axis. Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

public NDArray var(bool keepdims = false, int? ddof = null, DType dtype = null)

Parameters

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

ddof int?

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

dtype DType

Returns

NDArray

returns a new array containing the std values, otherwise a reference to the output array is returned.

Remarks

var(int, bool, int?, DType)

Compute the standard deviation along the specified axis. Returns the standard deviation, a measure of the spread of a distribution, of the array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.

public NDArray var(int axis, bool keepdims = false, int? ddof = null, DType dtype = null)

Parameters

axis int

Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array.

keepdims bool

If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

ddof int?

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

dtype DType

Returns

NDArray

returns a new array containing the std values, otherwise a reference to the output array is returned.

Remarks

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

Remarks

view<T>()

New view of array with the same data.

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

Returns

NDArray<T>

Type Parameters

T

Remarks

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 +(object, NDArray)

public static NDArray operator +(object left, NDArray right)

Parameters

left object
right NDArray

Returns

NDArray

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)

Element-wise 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 equal comparison with scalar (==).

public static NDArray<bool> operator ==(NDArray lhs, object rhs)

Parameters

lhs NDArray
rhs object

Returns

NDArray<bool>

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 ^(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)

public static explicit operator bool(NDArray nd)

Parameters

nd NDArray

Returns

bool

explicit operator byte(NDArray)

public static explicit operator byte(NDArray nd)

Parameters

nd NDArray

Returns

byte

explicit operator char(NDArray)

public static explicit operator char(NDArray nd)

Parameters

nd NDArray

Returns

char

explicit operator decimal(NDArray)

public static explicit operator decimal(NDArray nd)

Parameters

nd NDArray

Returns

decimal

explicit operator double(NDArray)

public static explicit operator double(NDArray nd)

Parameters

nd NDArray

Returns

double

explicit operator Half(NDArray)

public static explicit operator Half(NDArray nd)

Parameters

nd NDArray

Returns

Half

explicit operator short(NDArray)

public static explicit operator short(NDArray nd)

Parameters

nd NDArray

Returns

short

explicit operator int(NDArray)

public static explicit operator int(NDArray nd)

Parameters

nd NDArray

Returns

int

explicit operator long(NDArray)

public static explicit operator long(NDArray nd)

Parameters

nd NDArray

Returns

long

explicit operator Complex(NDArray)

public static explicit operator Complex(NDArray nd)

Parameters

nd NDArray

Returns

Complex

explicit operator sbyte(NDArray)

public static explicit operator sbyte(NDArray nd)

Parameters

nd NDArray

Returns

sbyte

explicit operator float(NDArray)

public static explicit operator float(NDArray nd)

Parameters

nd NDArray

Returns

float

explicit operator string(NDArray)

public static explicit operator string(NDArray d)

Parameters

d NDArray

Returns

string

explicit operator ushort(NDArray)

public static explicit operator ushort(NDArray nd)

Parameters

nd NDArray

Returns

ushort

explicit operator uint(NDArray)

public static explicit operator uint(NDArray nd)

Parameters

nd NDArray

Returns

uint

explicit operator ulong(NDArray)

public static explicit operator ulong(NDArray nd)

Parameters

nd NDArray

Returns

ulong

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 >(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 >=(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 >=(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>

implicit operator NDArray(Array)

public static implicit operator NDArray(Array array)

Parameters

array Array

Returns

NDArray

implicit operator NDArray(bool)

public static implicit operator NDArray(bool d)

Parameters

d bool

Returns

NDArray

implicit operator NDArray(byte)

public static implicit operator NDArray(byte d)

Parameters

d byte

Returns

NDArray

implicit operator NDArray(char)

public static implicit operator NDArray(char d)

Parameters

d char

Returns

NDArray

implicit operator NDArray(decimal)

public static implicit operator NDArray(decimal d)

Parameters

d decimal

Returns

NDArray

implicit operator NDArray(double)

public static implicit operator NDArray(double d)

Parameters

d double

Returns

NDArray

implicit operator NDArray(Half)

public static implicit operator NDArray(Half d)

Parameters

d Half

Returns

NDArray

implicit operator NDArray(short)

public static implicit operator NDArray(short d)

Parameters

d short

Returns

NDArray

implicit operator NDArray(int)

public static implicit operator NDArray(int d)

Parameters

d int

Returns

NDArray

implicit operator NDArray(long)

public static implicit operator NDArray(long d)

Parameters

d long

Returns

NDArray

implicit operator NDArray(Complex)

public static implicit operator NDArray(Complex d)

Parameters

d Complex

Returns

NDArray

implicit operator NDArray(sbyte)

public static implicit operator NDArray(sbyte d)

Parameters

d sbyte

Returns

NDArray

implicit operator NDArray(float)

public static implicit operator NDArray(float d)

Parameters

d float

Returns

NDArray

implicit operator NDArray(string)

public static implicit operator NDArray(string str)

Parameters

str string

Returns

NDArray

implicit operator NDArray(ushort)

public static implicit operator NDArray(ushort d)

Parameters

d ushort

Returns

NDArray

implicit operator NDArray(uint)

public static implicit operator NDArray(uint d)

Parameters

d uint

Returns

NDArray

implicit operator NDArray(ulong)

public static implicit operator NDArray(ulong d)

Parameters

d ulong

Returns

NDArray

operator !=(NDArray, NDArray)

Element-wise not-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 not-equal comparison with scalar (!=).

public static NDArray<bool> operator !=(NDArray lhs, object rhs)

Parameters

lhs NDArray
rhs object

Returns

NDArray<bool>

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 <<(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 np.asanyarray(object) (matches NumPy's PyArray_FromAny).

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 <(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 <=(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 <=(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 !(NDArray)

public static NDArray<bool> operator !(NDArray self)

Parameters

self NDArray

Returns

NDArray<bool>

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 *(object, NDArray)

public static NDArray operator *(object left, NDArray right)

Parameters

left object
right NDArray

Returns

NDArray

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 np.asanyarray(object) (matches NumPy's PyArray_FromAny).

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)

public static NDArray operator +(NDArray x)

Parameters

x NDArray

Returns

NDArray