Class np
- Namespace
- NumSharp
- Assembly
- NumSharp.dll
API bridge between NumSharp and Python NumPy
[ModuleName("np")]
[SuppressMessage("ReSharper", "StaticMemberInitializerReferesToMemberBelow")]
public static class np
- Inheritance
-
np
- Inherited Members
Fields
bool
public static readonly DType @bool
Field Value
bool8
public static readonly DType bool8
Field Value
bool_
public static readonly DType bool_
Field Value
byte
public static readonly DType @byte
Field Value
cdouble
public static readonly DType cdouble
Field Value
char
public static readonly DType @char
Field Value
clongdouble
public static readonly DType clongdouble
Field Value
complex128
public static readonly DType complex128
Field Value
complex_
public static readonly DType complex_
Field Value
decimal
NumSharp-only: the decimal descriptor (no NumPy counterpart).
public static readonly DType @decimal
Field Value
double
public static readonly DType @double
Field Value
float16
public static readonly DType float16
Field Value
float32
public static readonly DType float32
Field Value
float64
public static readonly DType float64
Field Value
float_
public static readonly DType float_
Field Value
half
public static readonly DType half
Field Value
int0
public static readonly DType int0
Field Value
int16
public static readonly DType int16
Field Value
int32
public static readonly DType int32
Field Value
int64
public static readonly DType int64
Field Value
int8
public static readonly DType int8
Field Value
int_
public static readonly DType int_
Field Value
intc
public static readonly DType intc
Field Value
intp
public static readonly DType intp
Field Value
long
public static readonly DType @long
Field Value
longlong
public static readonly DType longlong
Field Value
newaxis
A convenient alias for None, useful for indexing arrays.
public static readonly Slice newaxis
Field Value
Remarks
https://numpy.org/doc/stable/user/basics.indexing.html
https://stackoverflow.com/questions/42190783/what-does-three-dots-in-python-mean-when-indexing-what-looks-like-a-number
sbyte
public static readonly DType @sbyte
Field Value
short
public static readonly DType @short
Field Value
single
public static readonly DType single
Field Value
ubyte
public static readonly DType ubyte
Field Value
uint
public static readonly DType @uint
Field Value
uint0
public static readonly DType uint0
Field Value
uint16
public static readonly DType uint16
Field Value
uint32
public static readonly DType uint32
Field Value
uint64
public static readonly DType uint64
Field Value
uint8
public static readonly DType uint8
Field Value
uintc
public static readonly DType uintc
Field Value
uintp
public static readonly DType uintp
Field Value
ulong
public static readonly DType @ulong
Field Value
ulonglong
public static readonly DType ulonglong
Field Value
ushort
public static readonly DType @ushort
Field Value
Properties
BackendEngine
public static BackendType BackendEngine { get; set; }
Property Value
Inf
public static double Inf { get; }
Property Value
Infinity
public static double Infinity { get; }
Property Value
NAN
public static double NAN { get; }
Property Value
NINF
public static double NINF { get; }
Property Value
NaN
public static double NaN { get; }
Property Value
PINF
public static double PINF { get; }
Property Value
c_
Builds arrays by stacking columns — see np.CClass.
public static np.CClass c_ { get; }
Property Value
Remarks
chars
public static DType chars { get; }
Property Value
complex64
NumSharp does not support complex64 (two 32-bit floats). The only complex
type available is complex128 (two 64-bit floats, backed by
Complex). Accessing this property throws
NotSupportedException; use complex128 or
complex_ instead.
public static DType complex64 { get; }
Property Value
csingle
NumPy alias for complex64. Same as complex64 — throws because NumSharp does not support complex64.
public static DType csingle { get; }
Property Value
e
public static double e { get; }
Property Value
euler_gamma
public static double euler_gamma { get; }
Property Value
fft
Discrete Fourier Transform namespace — the port of Python's numpy.fft module.
Accessed exactly like Python: np.fft.fft(x), np.fft.rfft(x),
np.fft.fftfreq(n), etc. Mirrors the random facade shape (a lowercase
property returning a module object whose methods are the functions).
public static FourierModule fft { get; }
Property Value
Remarks
index_exp
NumPy's always-a-tuple twin of s_. Identical in C# — see np.IndexExpression for why.
public static np.IndexExpression index_exp { get; }
Property Value
Remarks
inf
public static double inf { get; }
Property Value
infinity
public static double infinity { get; }
Property Value
infty
public static double infty { get; }
Property Value
mgrid
Returns a dense multi-dimensional "meshgrid" when indexed — see np.MGridClass.
public static np.MGridClass mgrid { get; }
Property Value
Remarks
nan
public static double nan { get; }
Property Value
ogrid
Returns an open multi-dimensional "meshgrid" when indexed — see np.OGridClass.
public static np.OGridClass ogrid { get; }
Property Value
Remarks
pi
public static double pi { get; }
Property Value
r_
Builds arrays by concatenating along the first axis — see np.RClass.
public static np.RClass r_ { get; }
Property Value
Remarks
random
public static NumPyRandom random { get; }
Property Value
s_
Builds reusable index tuples: np.s_["2::2"] returns the index itself rather than
applying it, so it can be stored and handed to arr[…] later.
public static np.IndexExpression s_ { get; }
Property Value
Examples
var every2nd = np.s_["2::2"];
np.array(new[] {0, 1, 2, 3, 4})[every2nd]; // array([2, 4])
Remarks
Methods
abs(NDArray)
Calculate the absolute value element-wise.
np.abs is a shorthand for this function.
public static NDArray abs(NDArray a)
Parameters
aNDArrayInput value.
Returns
- NDArray
An ndarray containing the absolute value of each element in x.
Remarks
abs(NDArray, NDArray, NDArray, DType)
Calculate the absolute value element-wise (alias of absolute(NDArray, NDArray, NDArray, NPTypeCode?)).
Mirrors NumPy's ufunc signature: absolute(x, /, out=None, *, where=True, dtype=None).
public static NDArray abs(NDArray a, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
aNDArrayInput value.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the input must be same_kind-castable to it; for complex input it selects the magnitude dtype (float kinds only).
Returns
Remarks
absolute(NDArray)
Calculate the absolute value element-wise.
np.abs is a shorthand for this function.
public static NDArray absolute(NDArray a)
Parameters
aNDArrayInput value.
Returns
- NDArray
An ndarray containing the absolute value of each element in x.
Remarks
absolute(NDArray, NDArray, NDArray, DType)
Calculate the absolute value element-wise.
Mirrors NumPy's ufunc signature: absolute(x, /, out=None, *, where=True, dtype=None).
public static NDArray absolute(NDArray a, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
aNDArrayInput value.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the input must be same_kind-castable to it; for complex input it selects the magnitude dtype (float kinds only).
Returns
Remarks
acosh(NDArray, NDArray, NDArray, DType)
Inverse hyperbolic cosine, element-wise (Array-API alias of arccosh(NDArray, NDArray, NDArray, NPTypeCode?), added in NumPy 2.0).
public static NDArray acosh(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
Remarks
add(NDArray, NDArray, NDArray, NDArray, DType)
public static NDArray add(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayx2NDArrayoutNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDType
Returns
Remarks
all(NDArray)
Test whether all array elements evaluate to True.
public static bool all(NDArray a)
Parameters
aNDArrayInput array or object that can be converted to an array.
Returns
- bool
True if all elements evaluate to True (non-zero).
Remarks
all(NDArray, bool)
Test whether all array elements evaluate to True, optionally keeping reduced dimensions. Reduces over all axes (axis = None semantics).
public static NDArray<bool> all(NDArray nd, bool keepdims)
Parameters
ndNDArrayInput array.
keepdimsboolIf True, the result is broadcast-compatible with the input (every dimension becomes size 1). Otherwise the result is a 0-d array.
Returns
Remarks
all(NDArray, int, bool)
Test whether all array elements along a given axis evaluate to True.
public static NDArray<bool> all(NDArray nd, int axis, bool keepdims = false)
Parameters
ndNDArrayInput array or object that can be converted to an array.
axisintAxis along which a logical AND reduction is performed.
keepdimsboolIf True, the reduced axes are left in the result as dimensions with size one.
Returns
Remarks
all(NDArray, int[], NDArray, bool, NDArray)
Tuple-axis variant of the full np.all overload (with out and where).
public static NDArray all(NDArray a, int[] axis, NDArray @out, bool keepdims = false, NDArray where = null)
Parameters
aNDArrayInput array.
axisint[]Axes along which to reduce.
outNDArrayDestination array. Its dtype is preserved.
keepdimsboolIf True, reduced axes are left as size-one dimensions.
whereNDArrayBoolean mask, broadcastable against
a.
Returns
- NDArray
The reduced array, or
outwhen supplied.
Remarks
all(NDArray, int[], bool)
Test whether all array elements along the given axes evaluate to True. Multiple axes can be specified by passing an array of ints.
public static NDArray<bool> all(NDArray nd, int[] axis, bool keepdims = false)
Parameters
ndNDArrayInput array.
axisint[]Tuple of axes along which a logical AND reduction is performed. An empty array returns the input cast to bool (no reduction).
keepdimsboolIf True, the reduced axes are left in the result as dimensions with size one.
Returns
Remarks
all(NDArray, int?, NDArray, bool, NDArray)
Test whether all array elements along the given axis evaluate to True, with optional
out= destination and where= mask. Matches NumPy 2.x:
all(a, axis=None, out=None, keepdims=False, *, where=True).
public static NDArray all(NDArray a, int? axis = null, NDArray @out = null, bool keepdims = false, NDArray where = null)
Parameters
aNDArrayInput array.
axisint?Axis along which to reduce. Pass
nullfor axis=None (all axes).outNDArrayDestination array. Its dtype is preserved (e.g. an int
outstores 0/1 instead of bool). Passnullto allocate a fresh boolean array.keepdimsboolIf True, the reduced axes are left as dimensions with size one.
whereNDArrayBoolean (or numeric-treated-as-bool) mask, broadcastable against
a. Elements wherewhere=Falseare excluded from the reduction and contribute the identity value (True forall). Passnullfor no mask.
Returns
- NDArray
The reduced array, or
outwhen supplied.
Remarks
allclose(NDArray, NDArray, double, double, bool)
Returns True if two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers.The
relative difference (rtol * abs(b)) and the absolute difference
atol are added together to compare against the absolute difference
between a and b.
If either array contains one or more NaNs, False is returned.
Infs are treated as equal if they are in the same place and of the same
sign in both arrays.
public static bool allclose(NDArray a, NDArray b, double rtol = 1E-05, double atol = 1E-08, bool equal_nan = false)
Parameters
aNDArrayInput array to compare with b
bNDArrayInput array to compare with a.
rtoldoubleThe relative tolerance parameter(see Notes)
atoldoubleThe absolute tolerance parameter(see Notes)
equal_nanboolWhether to compare NaN's as equal. If True, NaN's in
awill be considered equal to NaN's inbin the output array.
Returns
amax(NDArray, int?, bool, DType)
Return the maximum of an array or maximum along an axis.
public static NDArray amax(NDArray a, int? axis = null, bool keepdims = false, DType dtype = null)
Parameters
aNDArrayaxisint?Axis or axes along which to operate.
keepdimsboolIf 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.
dtypeDTypethe 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>(NDArray)
Return the maximum of an array or maximum along an axis.
public static T amax<T>(NDArray a) where T : unmanaged
Parameters
aNDArray
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
Tthe type expected as a return, cast is performed if necessary.
Remarks
amin(NDArray, int?, bool, DType)
Return the minimum of an array or minimum along an axis.
public static NDArray amin(NDArray a, int? axis = null, bool keepdims = false, DType dtype = null)
Parameters
aNDArrayInput data.
axisint?Axis or axes along which to operate.
keepdimsboolIf 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.
dtypeDTypethe 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>(NDArray)
Return the minimum of an array or minimum along an axis.
public static T amin<T>(NDArray a) where T : unmanaged
Parameters
aNDArrayInput data.
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
Tthe type expected as a return, cast is performed if necessary.
Remarks
angle(NDArray, bool)
Return the angle (phase) of the complex argument, element-wise — the counterclockwise angle
from the positive real axis, in the range (-pi, pi]. One of the four basic complex-number
accessors (with real(NDArray), imag(NDArray) and conjugate(NDArray, NDArray, NDArray, DType)) — the
standard post-FFT PHASE spectrum: for A = np.fft.fft(a), np.angle(A) is the
phase spectrum.
public static NDArray angle(NDArray z, bool deg = false)
Parameters
zNDArrayA complex number or sequence of complex numbers (any real dtype is also accepted).
degboolReturn the angle in degrees if
true, radians (default) iffalse.
Returns
- NDArray
The phase angle, computed as
arctan2(imag, real)element-wise (so it follows the arctan2(NDArray, NDArray, NDArray, NDArray, System.Nullable<NPTypeCode>) IEEE conventions at magnitude zero and at the infinities). complex128 -> float64. A REAL input yields0for a positive value andpifor a negative one (arctan2(0, z)), with NumPy's per-dtype float tier: bool/int32+/float64/complex -> float64, int8/uint8/float16 -> float16, int16/uint16/float32 -> float32.
Remarks
any(NDArray)
Test whether any array element evaluates to True.
public static bool any(NDArray a)
Parameters
aNDArrayInput array or object that can be converted to an array.
Returns
- bool
True if any element evaluates to True (non-zero).
Remarks
any(NDArray, bool)
Test whether any array element evaluates to True, optionally keeping reduced dimensions. Reduces over all axes (axis = None semantics).
public static NDArray<bool> any(NDArray nd, bool keepdims)
Parameters
ndNDArrayInput array.
keepdimsboolIf True, the result has all dimensions as size 1 (broadcast-compatible with the input). Otherwise the result is a 0-d array.
Returns
Remarks
any(NDArray, int, bool)
Test whether any array element along a given axis evaluates to True.
public static NDArray<bool> any(NDArray nd, int axis, bool keepdims = false)
Parameters
ndNDArrayInput array.
axisintAxis along which a logical OR reduction is performed.
keepdimsboolIf True, the reduced axes are left in the result as dimensions with size one.
Returns
Remarks
any(NDArray, int[], NDArray, bool, NDArray)
Tuple-axis variant of the full np.any overload (with out and where).
public static NDArray any(NDArray a, int[] axis, NDArray @out, bool keepdims = false, NDArray where = null)
Parameters
aNDArrayInput array.
axisint[]Axes along which to reduce.
outNDArrayDestination array. Its dtype is preserved.
keepdimsboolIf True, reduced axes are left as size-one dimensions.
whereNDArrayBoolean mask, broadcastable against
a.
Returns
- NDArray
The reduced array, or
outwhen supplied.
Remarks
any(NDArray, int[], bool)
Test whether any array element along the given axes evaluates to True. Multiple axes can be specified by passing an array of ints.
public static NDArray<bool> any(NDArray nd, int[] axis, bool keepdims = false)
Parameters
ndNDArrayInput array.
axisint[]Tuple of axes along which a logical OR reduction is performed. An empty array returns the input cast to bool (no reduction).
keepdimsboolIf True, the reduced axes are left in the result as dimensions with size one.
Returns
Remarks
any(NDArray, int?, NDArray, bool, NDArray)
Test whether any array element along the given axis evaluates to True, with optional
out= destination and where= mask. Matches NumPy 2.x:
any(a, axis=None, out=None, keepdims=False, *, where=True).
public static NDArray any(NDArray a, int? axis = null, NDArray @out = null, bool keepdims = false, NDArray where = null)
Parameters
aNDArrayInput array.
axisint?Axis along which to reduce. Pass
nullfor axis=None (all axes).outNDArrayDestination array. Its dtype is preserved. Pass
nullto allocate fresh.keepdimsboolIf True, the reduced axes are left as size-one dimensions.
whereNDArrayBoolean (or numeric-treated-as-bool) mask, broadcastable against
a. Elements wherewhere=Falseare excluded from the reduction and contribute the identity value (False forany). Passnullfor no mask.
Returns
- NDArray
The reduced array, or
outwhen supplied.
Remarks
append(NDArray, NDArray, int?)
Append values to the end of arr.
public static NDArray append(NDArray arr, NDArray values, int? axis = null)
Parameters
arrNDArrayInput array.
valuesNDArrayValues to append. Shape must match
arron all dimensions exceptaxiswhenaxisis given; otherwise it is flattened.axisint?Axis along which to append.
null(default) flattens botharrandvaluesto 1-D before concatenation.
Returns
- NDArray
A new array with
valuesappended toarralongaxis.
Remarks
append(NDArray, object, int?)
Scalar / generic-value overload that wraps the value via
asanyarray(in object, DType, string) before delegating. Matches NumPy's
np.append([1,2,3], 4) idiom — the scalar is auto-coerced
to a 0-D ndarray (whose ravel is shape (1,)).
public static NDArray append(NDArray arr, object values, int? axis = null)
Parameters
Returns
arange(double)
Return evenly spaced values within a given interval.
public static NDArray arange(double stop)
Parameters
stopdoubleEnd of interval (exclusive).
Returns
- NDArray
Array of evenly spaced double values.
arange(double, DType, string)
Return evenly spaced values within a given interval.
public static NDArray arange(double stop, DType dtype, string device = null)
Parameters
stopdoubleEnd of interval (exclusive).
dtypeDTypeThe dtype of the output array (a Type, NPTypeCode, dtype string or DType — all convert implicitly).
devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity).
Returns
- NDArray
Array of evenly spaced values from 0 to stop-1.
Remarks
arange(double, double, DType, string)
Return evenly spaced values within a given interval.
public static NDArray arange(double start, double stop, DType dtype, string device = null)
Parameters
startdoubleStart of interval (inclusive).
stopdoubleEnd of interval (exclusive).
dtypeDTypeThe dtype of the output array (a Type, NPTypeCode, dtype string or DType — all convert implicitly).
devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity).
Returns
- NDArray
Array of evenly spaced values.
Remarks
arange(double, double, double)
Return evenly spaced values within a given interval.
public static NDArray arange(double start, double stop, double step = 1)
Parameters
startdoubleStart of interval (inclusive).
stopdoubleEnd of interval (exclusive).
stepdoubleSpacing between values. Default is 1.
Returns
- NDArray
Array of evenly spaced double values.
arange(double, double, double, DType, string)
Return evenly spaced values within a given interval.
Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop).
public static NDArray arange(double start, double stop, double step, DType dtype, string device = null)
Parameters
startdoubleStart of interval. The interval includes this value.
stopdoubleEnd of interval. The interval does not include this value.
stepdoubleSpacing between values. Default is 1.
dtypeDTypeThe dtype of the output array — one descriptor parameter, like NumPy's
dtype: a C# Type, an NPTypeCode, a NumPy dtype string ("f4") or a DType all convert implicitly. If null, infers from inputs (int64 for integers, float64 for floats).devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity).
Returns
- NDArray
Array of evenly spaced values.
Remarks
arange(int)
Return evenly spaced values within a given interval.
public static NDArray arange(int stop)
Parameters
stopintEnd of interval (exclusive).
Returns
- NDArray
Array of evenly spaced int64 values.
Remarks
NumPy 2.x returns int64 for integer arange.
arange(int, int, int)
Return evenly spaced values within a given interval.
public static NDArray arange(int start, int stop, int step = 1)
Parameters
startintStart of interval (inclusive).
stopintEnd of interval (exclusive).
stepintSpacing between values. Default is 1.
Returns
- NDArray
Array of evenly spaced int64 values.
Remarks
NumPy 2.x returns int64 for integer arange.
arange(long)
Return evenly spaced values within a given interval.
public static NDArray arange(long stop)
Parameters
stoplongEnd of interval (exclusive).
Returns
- NDArray
Array of evenly spaced int64 values.
Remarks
NumPy 2.x returns int64 for integer arange.
arange(long, long, long)
Return evenly spaced values within a given interval.
public static NDArray arange(long start, long stop, long step = 1)
Parameters
startlongStart of interval (inclusive).
stoplongEnd of interval (exclusive).
steplongSpacing between values. Default is 1.
Returns
- NDArray
Array of evenly spaced int64 values.
Remarks
NumPy 2.x returns int64 for integer arange.
arange(float)
Return evenly spaced values within a given interval.
public static NDArray arange(float stop)
Parameters
stopfloatEnd of interval (exclusive).
Returns
- NDArray
Array of evenly spaced float values.
arange(float, float, float)
Return evenly spaced values within a given interval.
public static NDArray arange(float start, float stop, float step = 1)
Parameters
startfloatStart of interval (inclusive).
stopfloatEnd of interval (exclusive).
stepfloatSpacing between values. Default is 1.
Returns
- NDArray
Array of evenly spaced float values.
arccos(NDArray, NDArray, NDArray, DType)
Trigonometric inverse cosine, element-wise.
The inverse of cos so that, if y = cos(x), then x = arccos(y).
public static NDArray arccos(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of, only non integer values are supported.
Returns
- NDArray
The angle of the ray intersecting the unit circle at the given x-coordinate in radians [0, pi]. This is a scalar if x is a scalar.
Remarks
arccosh(NDArray, NDArray, NDArray, DType)
Inverse hyperbolic cosine, element-wise.
The inverse of cosh so that, if y = cosh(x), then x = arccosh(y).
Mirrors NumPy's ufunc signature: arccosh(x, /, out=None, *, where=True, dtype=None).
public static NDArray arccosh(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs at this precision; integer/bool requests raise NumPy's "No loop matching" error.
Returns
- NDArray
Array of the same shape as x. This is a scalar if x is a scalar.
Remarks
arcsin(NDArray, NDArray, NDArray, DType)
Inverse sine, element-wise.
The convention is to return the angle z whose real part lies in [-pi/2, pi/2].
public static NDArray arcsin(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of, only non integer values are supported.
Returns
- NDArray
The inverse sine of each element in x, in radians and in the closed interval [-pi/2, pi/2]. This is a scalar if x is a scalar.
Remarks
arcsinh(NDArray, NDArray, NDArray, DType)
Inverse hyperbolic sine, element-wise.
The inverse of sinh so that, if y = sinh(x), then x = arcsinh(y).
Mirrors NumPy's ufunc signature: arcsinh(x, /, out=None, *, where=True, dtype=None).
public static NDArray arcsinh(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs at this precision; integer/bool requests raise NumPy's "No loop matching" error.
Returns
- NDArray
Array of the same shape as x. This is a scalar if x is a scalar.
Remarks
arctan(NDArray, NDArray, NDArray, DType)
Compute trigonometric inverse tangent, element-wise.
The inverse of tan, so that if y = tan(x) then x = arctan(y).
public static NDArray arctan(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of, only non integer values are supported.
Returns
- NDArray
Return has the same shape as x. Its real part is in [-pi/2, pi/2] (arctan(+/-inf) returns +/-pi/2). This is a scalar if x is a scalar.
Remarks
arctan2(NDArray, NDArray, NDArray, NDArray, DType)
Compute Element-wise arc tangent of x1/x2 choosing the quadrant correctly.
By IEEE convention, this function is defined for x2 = +/-0 and for either or both of x1 and x2 = +/-inf
public static NDArray arctan2(NDArray y, NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
yNDArrayxNDArrayInput array y-coordinates.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of, only non integer values are supported.
Returns
- NDArray
The Array of angles in radians, in the range [-pi, pi]. This is a scalar if both x1 and x2 are scalars.
Remarks
arctanh(NDArray, NDArray, NDArray, DType)
Inverse hyperbolic tangent, element-wise.
The inverse of tanh so that, if y = tanh(x), then x = arctanh(y).
Mirrors NumPy's ufunc signature: arctanh(x, /, out=None, *, where=True, dtype=None).
public static NDArray arctanh(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs at this precision; integer/bool requests raise NumPy's "No loop matching" error.
Returns
- NDArray
Array of the same shape as x. This is a scalar if x is a scalar.
Remarks
are_broadcastable(NDArray, NDArray)
Tests if these two two arrays are broadcastable against each other.
public static bool are_broadcastable(NDArray lhs, NDArray rhs)
Parameters
Returns
- bool
True if these can be broadcasted against each other.
Remarks
are_broadcastable(params NDArray[])
Tests if these two two arrays are broadcastable against each other.
public static bool are_broadcastable(params NDArray[] ndArrays)
Parameters
ndArraysNDArray[]The arrays to test for broadcasting.
Returns
- bool
True if these can be broadcasted against each other.
Remarks
are_broadcastable(params Shape[])
Tests if these two two arrays are broadcastable against each other.
public static bool are_broadcastable(params Shape[] shapes)
Parameters
shapesShape[]The shapes to test for broadcasting.
Returns
- bool
True if these can be broadcasted against each other.
Remarks
are_broadcastable(params int[][])
Tests if these two two arrays are broadcastable against each other.
public static bool are_broadcastable(params int[][] shapes)
Parameters
shapesint[][]The shapes to test for broadcasting.
Returns
- bool
True if these can be broadcasted against each other.
Remarks
are_broadcastable(long[], long[])
Tests if these two shapes are broadcastable against each other.
public static bool are_broadcastable(long[] shape1, long[] shape2)
Parameters
Returns
- bool
True if these can be broadcasted against each other.
Remarks
argmax(NDArray)
Returns the index of the maximum value.
public static long argmax(NDArray a)
Parameters
aNDArrayInput array.
Returns
- long
Index of the maximum value in the flattened array.
Remarks
argmax(NDArray, int, bool)
Returns the indices of the maximum values along an axis.
public static NDArray argmax(NDArray a, int axis, bool keepdims = false)
Parameters
aNDArrayInput array.
axisintBy default, the index is into the flattened array, otherwise along the specified axis.
keepdimsboolIf 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(NDArray)
Returns the index of the minimum value.
public static long argmin(NDArray a)
Parameters
aNDArrayInput array.
Returns
- long
Index of the minimum value in the flattened array.
Remarks
argmin(NDArray, int, bool)
Returns the indices of the minimum values along an axis.
public static NDArray argmin(NDArray a, int axis, bool keepdims = false)
Parameters
aNDArrayInput array.
axisintBy default, the index is into the flattened array, otherwise along the specified axis.
keepdimsboolIf 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, NDArray, int?, string, string)
Indirect partition with the kth indices given as an ARRAY — NumPy's array-kth form (bool kth "Booleans unacceptable as partition index"; non-integer "Partition index must be integer"; >1-D "object too deep for desired array" BEFORE the axis check; uint64 values wrap modulo 2^64 exactly like NumPy's intp cast).
public static NDArray argpartition(NDArray a, NDArray kth, int? axis = -1, string kind = "introselect", string order = null)
Parameters
Returns
Remarks
argpartition(NDArray, int, int?, string, string)
Perform an indirect partition along the given axis: returns int64 indices of the same
shape that index a along axis in partitioned
order — a[result[kth]] is the element that would sit at kth
in a sorted array (NumPy np.argpartition). The input is only read.
public static NDArray argpartition(NDArray a, int kth, int? axis = -1, string kind = "introselect", string order = null)
Parameters
aNDArrayArray to partition indirectly.
kthintElement index to partition by; negative wraps from the end.
axisint?Axis to partition along. -1 (default) = last axis; null flattens first (indices then address the flattened array).
kindstringSelection algorithm — only 'introselect' exists.
orderstringMust stay null (no structured dtypes).
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.argpartition.html
A 0-d input ravels to shape (1,) first — NumPy's arg-side quirk (its axis/kth errors
then report dimension/size 1, and the result is [0]), unlike np.partition which
raises AxisError on 0-d. NaN floats partition to the end (their indices keep encounter
order, the same policy as argsort's NaN tail).
argpartition(NDArray, int[], int?, string, string)
Indirect partition around EVERY index in kth at once (NumPy
np.argpartition with a kth sequence). Returns int64 indices; the input is only read.
public static NDArray argpartition(NDArray a, int[] kth, int? axis = -1, string kind = "introselect", string order = null)
Parameters
Returns
Remarks
argsort(NDArray, int?)
Returns the indices that would sort nd along axis
(default last; null flattens). Returns int64 indices. NumPy np.argsort.
public static NDArray argsort(NDArray nd, int? axis = -1)
Parameters
Returns
argsort<T>(NDArray, int)
Returns the indices that would sort an array.
Perform an indirect sort along the given axis using the algorithm specified by the kind keyword.It returns an array of indices of the same shape as a that index data along the given axis in sorted order.
public static NDArray argsort<T>(NDArray nd, int axis = -1) where T : unmanaged
Parameters
Returns
Type Parameters
T
argwhere(NDArray)
Find the indices of array elements that are non-zero, grouped by element.
public static NDArray argwhere(NDArray a)
Parameters
aNDArrayInput array.
Returns
- NDArray
Indices of elements that are non-zero, grouped per element. The result is a 2-D array of shape
(N, a.ndim)whereNis the number of non-zero elements. Each row contains the coordinates of one non-zero element. Result dtype isint64. For 0-d input, returns shape(1, 0)when the value is truthy and(0, 0)otherwise. For empty input of shape(0, d1, ..., dn), returns shape(0, ndim).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.argwhere.html
Equivalent to np.transpose(np.nonzero(a)) with a special case for 0-d input.
Distinct from nonzero(NDArray) which returns a tuple of column arrays.
around(NDArray, int, NDArray, DType)
Evenly round to the given number of decimals (alias of round_(NDArray, int, NDArray, DType); NumPy: np.around is np.round).
public static NDArray around(NDArray x, int decimals = 0, NDArray @out = null, DType dtype = null)
Parameters
xNDArrayInput array.
decimalsintNumber of decimal places to round to (default 0). Half is rounded to even.
outNDArrayA location into which the result is stored; must be the correct shape, returned as-is (out= only — see round_(NDArray, int, NDArray, DType)).
dtypeDTypeThe DType the returned ndarray should be of (implicit from Type / NPTypeCode / NumPy dtype string).
Returns
- NDArray
An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned. The real and imaginary parts of complex numbers are rounded separately. The result of rounding a float is a float.
Remarks
array(NDArray, bool)
Create an array from an existing NDArray. Matches NumPy's default
np.array(a) which always copies (NumPy 2.x: copy=True by default).
public static NDArray array(NDArray nd, bool copy = true)
Parameters
ndNDArraySource array.
copyboolWhen
true(default) the source storage is cloned; whenfalsethe storage is shared (alias). For "copy only if needed" semantics use asarray(NDArray, Type, char, bool?, NDArray, string).
Returns
Remarks
array(MemoryView, bool)
Create an array from a np.MemoryView (obtained from data) —
the consumer round-trip of ndarray.data. Matches NumPy's np.array(a.data),
which reads the buffer's shape/strides/dtype and (by default) COPIES, preserving the
source's N-D shape and layout. Equivalent to np.array(buffer.obj, copy); a copy is
always writeable, even from a read-only (broadcast) source.
public static NDArray array(np.MemoryView buffer, bool copy = true)
Parameters
buffernp.MemoryViewA np.MemoryView over an array.
copyboolWhen
true(default) the source storage is cloned; whenfalsethe storage is shared (alias).
Returns
Remarks
array(Array, DType, int, bool, char)
Creates an NDArray from an array with an unknown size or dtype.
[SuppressMessage("ReSharper", "InvalidXmlDocComment")]
public static NDArray array(Array array, DType dtype = null, int ndmin = 0, bool copy = true, char order = 'C')
Parameters
arrayArraydtypeDTypendminintSpecifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement.
copyboolAlways copies if the array is larger than 1-d.
ordercharMemory layout: 'C' (row-major, default), 'F' (column-major), 'A'/'K' (resolved from source).
Returns
Remarks
array(string)
public static NDArray array(string chars)
Parameters
charsstring
Returns
array(string[])
Create a vector ndarray of type <xref href="System.String" data-throw-if-not-resolved="false"></xref>.
Encode string array. format: [numOfRow lenOfRow1 lenOfRow2 contents] sample: [2 2 4 aacccc]
public static NDArray array(string[] strArray)
Parameters
strArraystring[]
Returns
array2string(NDArray, int?, int?, bool?, string, string, int?, int?, char?, string, string)
Return a string representation of an array (NumPy's np.array2string).
public static string array2string(NDArray a, int? max_line_width = null, int? precision = null, bool? suppress_small = null, string separator = " ", string prefix = "", int? threshold = null, int? edgeitems = null, char? sign = null, string floatmode = null, string suffix = "")
Parameters
aNDArrayInput array.
max_line_widthint?Inserts newlines if text is longer than this. Defaults to the current linewidth.
precisionint?Floating point precision. Defaults to the current precision.
suppress_smallbool?Represent numbers very close to zero as zero. Defaults to the current option.
separatorstringInserted between elements (default " ").
prefixstringUsed to align/wrap the output; its content is not included.
thresholdint?Total number of elements which trigger summarization.
edgeitemsint?Number of items at the beginning and end of each dimension in summary.
signchar?'-', '+', or ' '.
floatmodestringOne of "fixed", "unique", "maxprec", "maxprec_equal".
suffixstringUsed to wrap the output; its content is not included.
Returns
Remarks
array_equal(NDArray, NDArray)
True if two arrays have the same shape and elements, False otherwise.
public static bool array_equal(NDArray a, NDArray b)
Parameters
Returns
- bool
Returns True if the arrays are equal.
Remarks
array_repr(NDArray, int?, int?, bool?)
Return the string representation of an array (NumPy's np.array_repr).
public static string array_repr(NDArray a, int? max_line_width = null, int? precision = null, bool? suppress_small = null)
Parameters
Returns
Remarks
array_split(NDArray, int, int)
Split an array into multiple sub-arrays.
public static NDArray[] array_split(NDArray ary, int indices_or_sections, int axis = 0)
Parameters
Returns
- NDArray[]
Remarks
The only difference between split and array_split is that array_split allows indices_or_sections to be an integer that does not equally divide the axis. https://numpy.org/doc/stable/reference/generated/numpy.array_split.html
array_split(NDArray, int[], int)
Split an array into multiple sub-arrays.
public static NDArray[] array_split(NDArray ary, int[] indices, int axis = 0)
Parameters
Returns
- NDArray[]
array_split(NDArray, long[], int)
Split an array into multiple sub-arrays.
public static NDArray[] array_split(NDArray ary, long[] indices, int axis = 0)
Parameters
Returns
- NDArray[]
array_str(NDArray, int?, int?, bool?)
Return a string representation of the data in an array (NumPy's np.array_str).
public static string array_str(NDArray a, int? max_line_width = null, int? precision = null, bool? suppress_small = null)
Parameters
Returns
Remarks
array<T>(IEnumerable<T>)
Creates a Vector NDArray from given data.
public static NDArray array<T>(IEnumerable<T> data) where T : unmanaged
Parameters
dataIEnumerable<T>The enumeration of data to create NDArray from.
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.array.html
Always performs a copy.
array<T>(IEnumerable<T>, int)
Creates a Vector NDArray from given data.
public static NDArray array<T>(IEnumerable<T> data, int size) where T : unmanaged
Parameters
dataIEnumerable<T>The enumeration of data to create NDArray from.
sizeintMaximum number of items to read from
data.
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.array.html
Always performs a copy.
size can be used to limit the amount of items to read form data. Reading stops on either size or data ends.
array<T>(IEnumerable<T>, long)
Creates a Vector NDArray from given data.
public static NDArray array<T>(IEnumerable<T> data, long size) where T : unmanaged
Parameters
dataIEnumerable<T>The enumeration of data to create NDArray from.
sizelongMaximum number of items to read from
data.
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.array.html
Always performs a copy.
size can be used to limit the amount of items to read form data. Reading stops on either size or data ends.
array<T>(T)
Creates a scalar (0-dimensional) NDArray from a single value.
public static NDArray array<T>(T scalar) where T : unmanaged
Parameters
scalarTThe scalar value.
Returns
Type Parameters
TThe type of the value, must be compliant to numpy's supported dtypes.
Remarks
NumPy: np.array(42) creates a 0-dimensional array with shape (). https://numpy.org/doc/stable/reference/generated/numpy.array.html
array<T>(T[,,,,,,,,,,,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,,,,,,,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,,,,,,,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,,,,,,,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,,,,,,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,,,,,,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,,,,,,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,,,,,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,,,,,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,,,,,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,,,,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,,,,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,,,,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,,,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,,,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,,,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,], DType)
Creates an NDArray from given data with specified dtype.
public static NDArray array<T>(T[,] data, DType dtype) where T : unmanaged
Parameters
dataT[,]The array to create NDArray from.
dtypeDTypeThe desired dtype for the array — one descriptor parameter, like NumPy's
dtype: a C# Type, an NPTypeCode, a NumPy dtype string ("f4") or a DType all convert implicitly. If different fromT, the data will be cast.
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[,], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[,] data, bool copy = true) where T : unmanaged
Parameters
dataT[,]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(params T[])
Creates a Vector NDArray from given data.
public static NDArray array<T>(params T[] data) where T : unmanaged
Parameters
dataT[]The array to create NDArray from.
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.array.html
Always performs a copy.
array<T>(T[], DType)
Creates a Vector NDArray from given data with specified dtype.
public static NDArray array<T>(T[] data, DType dtype) where T : unmanaged
Parameters
dataT[]The array to create NDArray from.
dtypeDTypeThe desired dtype for the array — one descriptor parameter, like NumPy's
dtype: a C# Type, an NPTypeCode, a NumPy dtype string ("f4") or a DType all convert implicitly. If different fromT, the data will be cast.
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[], bool)
Creates an NDArray from given data.
public static NDArray array<T>(T[] data, bool copy) where T : unmanaged
Parameters
dataT[]The array to create NDArray from.
copyboolIf true then the array will be copied to a newly allocated memory.
If false then the array will be pinned by calling Alloc(object).
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
array<T>(T[][])
Creates an NDArray from given data.
[SuppressMessage("ReSharper", "SuggestVarOrType_SimpleTypes")]
[SuppressMessage("ReSharper", "SuggestVarOrType_Elsewhere")]
public static NDArray array<T>(T[][] data) where T : unmanaged
Parameters
dataT[][]The array to create NDArray from. Shape is taken from the first item of each array/nested array.
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.array.html
Always performs a copy.
array<T>(T[][][])
Creates an NDArray from given data.
[SuppressMessage("ReSharper", "SuggestVarOrType_SimpleTypes")]
[SuppressMessage("ReSharper", "SuggestVarOrType_Elsewhere")]
public static NDArray array<T>(T[][][] data) where T : unmanaged
Parameters
dataT[][][]The array to create NDArray from. Shape is taken from the first item of each array/nested array.
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.array.html
Always performs a copy.
array<T>(T[][][][])
Creates an NDArray from given data.
[SuppressMessage("ReSharper", "SuggestVarOrType_SimpleTypes")]
[SuppressMessage("ReSharper", "SuggestVarOrType_Elsewhere")]
public static NDArray array<T>(T[][][][] data) where T : unmanaged
Parameters
dataT[][][][]The array to create NDArray from. Shape is taken from the first item of each array/nested array.
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.array.html
Always performs a copy.
array<T>(T[][][][][])
Creates an NDArray from given data.
[SuppressMessage("ReSharper", "SuggestVarOrType_SimpleTypes")]
[SuppressMessage("ReSharper", "SuggestVarOrType_Elsewhere")]
public static NDArray array<T>(T[][][][][] data) where T : unmanaged
Parameters
dataT[][][][][]The array to create NDArray from. Shape is taken from the first item of each array/nested array.
Returns
Type Parameters
TThe type of given array, must be compliant to numpy's supported dtypes.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.array.html
Always performs a copy.
asanyarray(MemoryView, DType, char, string)
Convert a np.MemoryView (obtained from data) to an ndarray,
passing ndarray subclasses through — the consumer round-trip of ndarray.data. Matches
NumPy's np.asanyarray(a.data) (a zero-copy VIEW sharing memory, copying only if a
dtype/layout change forces it). A dedicated overload is required because a np.MemoryView
is not otherwise resolvable by the object converter above. Equivalent to
np.asanyarray(buffer.obj, …).
public static NDArray asanyarray(np.MemoryView buffer, DType dtype = null, char order = 'K', string device = null)
Parameters
buffernp.MemoryViewA np.MemoryView over an array.
dtypeDTypeBy default, the data-type is inferred from the source.
orderchar'C', 'F', 'A' or 'K' (default).
devicestringOnly
"cpu"andnullare accepted (Array-API parity).
Returns
Remarks
asanyarray(in object, DType, char, string)
Convert the input to an ndarray with a specified memory layout.
public static NDArray asanyarray(in object a, DType dtype, char order, string device = null)
Parameters
aobjectInput data.
dtypeDTypeBy default, the data-type is inferred from the input data.
orderchar'C', 'F', 'A' or 'K' (default — resolved against a).
devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity).
Returns
- NDArray
Array interpretation of a in the requested layout.
Remarks
asanyarray(in object, DType, string)
Convert the input to an ndarray, but pass ndarray subclasses through.
public static NDArray asanyarray(in object a, DType dtype = null, string device = null)
Parameters
aobjectInput data, in any form that can be converted to an array. This includes scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists, and ndarrays.
dtypeDTypeBy default, the data-type is inferred from the input data.
devicestring
Returns
- NDArray
Array interpretation of a. If a is an ndarray or a subclass of ndarray, it is returned as-is and no copy is performed.
Remarks
asarray(NDArray, DType, char, bool?, NDArray, string)
Convert the input to an ndarray, matching NumPy 2.x semantics.
If a already satisfies the requested dtype/layout, it is returned as-is — no copy.
public static NDArray asarray(NDArray a, DType dtype = null, char order = 'K', bool? copy = null, NDArray like = null, string device = null)
Parameters
aNDArrayInput ndarray.
dtypeDTypeRequested dtype.
nullkeeps the input dtype.orderchar'C' (row-major), 'F' (column-major), 'A' (any contiguous), 'K' (keep — default). 'A'/'K' never force a copy on layout grounds.
copybool?Tri-state:
null= copy only if needed (default),true= always copy,false= never copy (raises if a copy would be required).likeNDArrayReference array for array-function dispatch — accepted for NumPy parity but has no observable effect in NumSharp.
devicestringTarget device. Only
"cpu"andnullare accepted.
Returns
- NDArray
NDArray with the requested dtype and memory layout. Returns
awhen no copy is needed.
Remarks
asarray(MemoryView, DType, char, bool?, NDArray, string)
Convert a np.MemoryView (obtained from data) to an ndarray —
the consumer round-trip of ndarray.data. Matches NumPy's np.asarray(a.data),
which reads the buffer's shape/strides/dtype and returns a zero-copy VIEW sharing its memory
(copying only if a dtype/layout change forces it), preserving the source's N-D shape and
layout. Equivalent to np.asarray(buffer.obj, …).
public static NDArray asarray(np.MemoryView buffer, DType dtype = null, char order = 'K', bool? copy = null, NDArray like = null, string device = null)
Parameters
buffernp.MemoryViewA np.MemoryView over an array.
dtypeDTypeRequested dtype.
nullkeeps the source dtype.orderchar'C', 'F', 'A', or 'K' (default).
copybool?Tri-state copy:
null= if-needed,true= always,false= never (raises).likeNDArrayReference for array-function dispatch — accepted for parity, no effect.
devicestringOnly
"cpu"ornull.
Returns
Remarks
asarray(MemoryView, string, char, bool?, NDArray, string)
Convert a np.MemoryView to an ndarray, taking a NumPy-style dtype string
(e.g. "float32", "<i4"). See
asarray(MemoryView, Type, char, bool?, NDArray, string).
public static NDArray asarray(np.MemoryView buffer, string dtype, char order = 'K', bool? copy = null, NDArray like = null, string device = null)
Parameters
Returns
Remarks
asarray(string)
public static NDArray asarray(string data)
Parameters
datastring
Returns
asarray(string[], int)
public static NDArray asarray(string[] data, int ndim = 1)
Parameters
Returns
asarray_chkfinite(NDArray, DType, char)
Convert the input to an array, checking for NaNs or Infs.
public static NDArray asarray_chkfinite(NDArray a, DType dtype = null, char order = 'K')
Parameters
aNDArrayInput data. No copy is performed if the input is already an ndarray matching the requested dtype/order.
dtypeDTypeBy default, the data-type is inferred from the input data.
orderchar'C' (row-major), 'F' (column-major), 'A' (any), 'K' (keep — default, equivalent to NumPy's
order=None).
Returns
- NDArray
Array interpretation of
a.
Remarks
Mirrors NumPy 2.x numpy.asarray_chkfinite(a, dtype=None, order=None): the finiteness
check runs ONLY for float-family dtypes (Half/Single/Double/Complex — NumPy's
typecodes['AllFloat']), since integer, boolean, char and decimal arrays can never
hold inf/NaN. Complex is finite iff both its real and imaginary parts are finite.
https://numpy.org/doc/stable/reference/generated/numpy.asarray_chkfinite.html
Exceptions
- ValueError
If
acontains NaN (Not a Number) or Inf (Infinity).
asarray<T>(T)
public static NDArray asarray<T>(T data) where T : struct
Parameters
dataT
Returns
Type Parameters
T
asarray<T>(T[], int)
public static NDArray asarray<T>(T[] data, int ndim = 1) where T : struct
Parameters
dataT[]ndimint
Returns
Type Parameters
T
ascontiguousarray(NDArray, DType)
Return a contiguous array (ndim >= 1) in memory (C order).
public static NDArray ascontiguousarray(NDArray a, DType dtype = null)
Parameters
Returns
- NDArray
Contiguous array of same shape and content as a, with type dtype if specified.
Remarks
ascontiguousarray(MemoryView, DType)
Return a C-contiguous array from a np.MemoryView (obtained from
data) — the consumer round-trip of ndarray.data. Matches NumPy's
np.ascontiguousarray(a.data): a zero-copy VIEW when the source is already C-contiguous,
otherwise a C-order copy. Equivalent to np.ascontiguousarray(buffer.obj, dtype).
public static NDArray ascontiguousarray(np.MemoryView buffer, DType dtype = null)
Parameters
buffernp.MemoryViewA np.MemoryView over an array.
dtypeDTypeBy default, the data-type is inferred from the source.
Returns
Remarks
asfortranarray(NDArray, DType)
Return an array (ndim >= 1) laid out in Fortran order in memory.
public static NDArray asfortranarray(NDArray a, DType dtype = null)
Parameters
Returns
- NDArray
The input a in Fortran, or column-major, order.
Remarks
asfortranarray(MemoryView, DType)
Return a Fortran-ordered array from a np.MemoryView (obtained from
data) — the consumer round-trip of ndarray.data. Matches NumPy's
np.asfortranarray(a.data): a zero-copy VIEW when the source is already F-contiguous,
otherwise an F-order copy. Equivalent to np.asfortranarray(buffer.obj, dtype).
public static NDArray asfortranarray(np.MemoryView buffer, DType dtype = null)
Parameters
buffernp.MemoryViewA np.MemoryView over an array.
dtypeDTypeBy default, the data-type is inferred from the source.
Returns
Remarks
asinh(NDArray, NDArray, NDArray, DType)
Inverse hyperbolic sine, element-wise (Array-API alias of arcsinh(NDArray, NDArray, NDArray, NPTypeCode?), added in NumPy 2.0).
public static NDArray asinh(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
Remarks
asmatrix(NDArray, DType)
Interpret the input as a matrix — a 2-D array. Unlike a copy, asmatrix does not copy
if the input is already an ndarray; it returns a 2-D view that shares memory.
public static NDArray asmatrix(NDArray data, DType dtype = null)
Parameters
Returns
- NDArray
datainterpreted as a 2-D array. A 0-D input becomes shape(1, 1), a 1-D input of length N becomes(1, N), and a 2-D input is returned unchanged.
Remarks
Port of NumPy 2.x numpy.asmatrix ≙ matrix(data, copy=False). NumSharp has no
dedicated matrix subclass (NumPy's is pending-deprecated), so the result is a plain
2-D NDArray — the special matrix operators (* as matmul, ** as
matrix power, .H, .I) are NOT provided. The dimensional coercion matches NumPy's
matrix.array_finalize exactly, including the >2-D behaviour: axes of length 1 are
dropped and the result must then be 2-D, otherwise a ValueError
("shape too large to be a matrix.") is raised. The view is preserved for strided, transposed
and reversed inputs (no copy). A dtype change casts (which copies), then coerces the copy.
https://numpy.org/doc/stable/reference/generated/numpy.asmatrix.html
asmatrix(string, DType)
Interpret a matrix string as a 2-D array. Rows are separated by ';' and columns by
commas and/or whitespace, e.g. "1 2; 3 4". Surrounding brackets are ignored. The dtype
is inferred (integer when every element is an integer, otherwise double) unless
dtype is given.
public static NDArray asmatrix(string data, DType dtype = null)
Parameters
datastringMatrix string such as
"1 2; 3 4".dtypeDTypeData-type of the output.
nullinfers it from the values.
Returns
Remarks
Exceptions
- ValueError
If the rows are not all the same length.
asscalar(NDArray)
Convert an array of size 1 to its scalar equivalent.
[Obsolete("np.asscalar is deprecated (removed in NumPy 2.0). Use NDArray.item() instead.")]
public static object asscalar(NDArray nd)
Parameters
ndNDArrayInput NDArray of size 1.
Returns
Remarks
DEPRECATED: np.asscalar was removed in NumPy 2.0.
asscalar(Array)
Convert an array of size 1 to its scalar equivalent.
[Obsolete("np.asscalar is deprecated (removed in NumPy 2.0). Use NDArray.item() instead.")]
public static object asscalar(Array arr)
Parameters
arrArrayInput array of size 1.
Returns
Remarks
DEPRECATED: np.asscalar was removed in NumPy 2.0.
asscalar<T>(ArraySlice<T>)
Convert an array of size 1 to its scalar equivalent.
[Obsolete("np.asscalar is deprecated (removed in NumPy 2.0). Use NDArray.item() instead.")]
public static T asscalar<T>(ArraySlice<T> arr) where T : unmanaged
Parameters
arrArraySlice<T>Input array of size 1.
Returns
- T
Type Parameters
T
Remarks
DEPRECATED: np.asscalar was removed in NumPy 2.0.
asscalar<T>(IArraySlice)
Convert an array of size 1 to its scalar equivalent.
[Obsolete("np.asscalar is deprecated (removed in NumPy 2.0). Use NDArray.item() instead.")]
public static T asscalar<T>(IArraySlice arr) where T : unmanaged
Parameters
arrIArraySliceInput array of size 1.
Returns
- T
Type Parameters
T
Remarks
DEPRECATED: np.asscalar was removed in NumPy 2.0.
asscalar<T>(NDArray)
Convert an array of size 1 to its scalar equivalent.
[Obsolete("np.asscalar is deprecated (removed in NumPy 2.0). Use NDArray.item() instead.")]
public static T asscalar<T>(NDArray nd) where T : unmanaged
Parameters
ndNDArrayInput NDArray of size 1.
Returns
- T
Type Parameters
T
Remarks
DEPRECATED: np.asscalar was removed in NumPy 2.0. Use NDArray.item() instead: arr.item() or arr.item<T>() https://numpy.org/doc/stable/reference/generated/numpy.ndarray.item.html
asscalar<T>(Array)
Convert an array of size 1 to its scalar equivalent.
[Obsolete("np.asscalar is deprecated (removed in NumPy 2.0). Use NDArray.item() instead.")]
public static T asscalar<T>(Array arr)
Parameters
arrArrayInput array of size 1.
Returns
- T
Type Parameters
T
Remarks
DEPRECATED: np.asscalar was removed in NumPy 2.0.
atanh(NDArray, NDArray, NDArray, DType)
Inverse hyperbolic tangent, element-wise (Array-API alias of arctanh(NDArray, NDArray, NDArray, NPTypeCode?), added in NumPy 2.0).
public static NDArray atanh(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
Remarks
atleast_1d(NDArray)
Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved.
public static NDArray atleast_1d(NDArray arr)
Parameters
arrNDArray
Returns
- NDArray
An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary.
Remarks
atleast_1d(params NDArray[])
Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved.
public static NDArray[] atleast_1d(params NDArray[] arys)
Parameters
arysNDArray[]One or more input arrays.
Returns
- NDArray[]
An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary.
Remarks
atleast_1d(object)
Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved.
public static NDArray atleast_1d(object arys)
Parameters
arysobjectOne or more input arrays.
Returns
- NDArray
An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary.
Remarks
atleast_1d(params object[])
Convert inputs to arrays with at least one dimension. Scalar inputs are converted to 1-dimensional arrays, whilst higher-dimensional inputs are preserved.
public static NDArray[] atleast_1d(params object[] arys)
Parameters
arysobject[]One or more input arrays.
Returns
- NDArray[]
An array, or list of arrays, each with a.ndim >= 1. Copies are made only if necessary.
Remarks
atleast_2d(NDArray)
View inputs as arrays with at least two dimensions.
public static NDArray atleast_2d(NDArray arr)
Parameters
arrNDArrayOne or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved.
Returns
- NDArray
An array, or list of arrays, each with a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned.
Remarks
atleast_2d(params NDArray[])
View inputs as arrays with at least two dimensions.
public static NDArray[] atleast_2d(params NDArray[] arys)
Parameters
arysNDArray[]One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved.
Returns
- NDArray[]
An array, or list of arrays, each with a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned.
Remarks
atleast_2d(object)
View inputs as arrays with at least two dimensions.
public static NDArray atleast_2d(object arys)
Parameters
arysobjectOne or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved.
Returns
- NDArray
An array, or list of arrays, each with a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned.
Remarks
atleast_2d(params object[])
View inputs as arrays with at least two dimensions.
public static NDArray[] atleast_2d(params object[] arys)
Parameters
arysobject[]One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have two or more dimensions are preserved.
Returns
- NDArray[]
An array, or list of arrays, each with a.ndim >= 2. Copies are avoided where possible, and views with two or more dimensions are returned.
Remarks
atleast_3d(NDArray)
View inputs as arrays with at least three dimensions.
public static NDArray atleast_3d(NDArray arr)
Parameters
arrNDArray
Returns
- NDArray
An array, or list of arrays, each with a.ndim >= 3. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1).
Remarks
atleast_3d(params NDArray[])
View inputs as arrays with at least three dimensions.
public static NDArray[] atleast_3d(params NDArray[] arys)
Parameters
arysNDArray[]One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved.
Returns
- NDArray[]
An array, or list of arrays, each with a.ndim >= 3. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1).
Remarks
atleast_3d(object)
View inputs as arrays with at least three dimensions.
public static NDArray atleast_3d(object arys)
Parameters
arysobjectOne or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved.
Returns
- NDArray
An array, or list of arrays, each with a.ndim >= 3. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1).
Remarks
atleast_3d(params object[])
View inputs as arrays with at least three dimensions.
public static NDArray[] atleast_3d(params object[] arys)
Parameters
arysobject[]One or more array-like sequences. Non-array inputs are converted to arrays. Arrays that already have three or more dimensions are preserved.
Returns
- NDArray[]
An array, or list of arrays, each with a.ndim >= 3. Copies are avoided where possible, and views with three or more dimensions are returned. For example, a 1-D array of shape (N,) becomes a view of shape (1, N, 1), and a 2-D array of shape (M, N) becomes a view of shape (M, N, 1).
Remarks
average(NDArray, int[], NDArray, bool)
Compute the weighted average along a tuple of axes. Equivalent to
np.average(a, axis, weights, keepdims) in NumPy with a tuple axis.
public static NDArray average(NDArray a, int[] axis, NDArray weights = null, bool keepdims = false)
Parameters
Returns
Remarks
average(NDArray, int?, NDArray, bool)
Compute the weighted average along the specified axis.
Equivalent to sum(a * weights) / sum(weights). When weights
is null this reduces to mean(NDArray) over the same axes.
public static NDArray average(NDArray a, int? axis = null, NDArray weights = null, bool keepdims = false)
Parameters
Returns
Remarks
average_returned(NDArray, int[], NDArray, bool)
Tuple-axis overload of average_returned(NDArray, int?, NDArray, bool).
public static (NDArray avg, NDArray sumOfWeights) average_returned(NDArray a, int[] axis, NDArray weights = null, bool keepdims = false)
Parameters
Returns
Remarks
average_returned(NDArray, int?, NDArray, bool)
Compute the weighted average and return a tuple (avg, sum_of_weights).
Equivalent to numpy.average(..., returned=True). When weights
is null, sum_of_weights is the number of elements per output cell
(broadcast to the average's shape).
public static (NDArray avg, NDArray sumOfWeights) average_returned(NDArray a, int? axis = null, NDArray weights = null, bool keepdims = false)
Parameters
Returns
Remarks
bincount(NDArray, NDArray, int)
Count the number of occurrences of each non-negative integer in x.
With no weights, bincount(x)[i] is the number of times the
value i appears in x (dtype int64). With
weights, bincount(x, w)[i] is the sum of w[j] for all
j where x[j] == i (dtype float64). The output length is
max(x.max() + 1, minlength).
public static NDArray bincount(NDArray x, NDArray weights = null, int minlength = 0)
Parameters
xNDArray1-D array of non-negative integers. Integer/bool/char dtypes are cast to
int64; a float/complex/decimal input raises (matching NumPy's behaviour for an actualndarrayof a non-integer dtype).weightsNDArrayOptional 1-D array of weights, same length as
x, cast tofloat64. When present the result is a weighted sum per bin instead of a count.minlengthintMinimum length of the output array. Must be non-negative.
Returns
- NDArray
A 1-D array:
int64counts whenweightsis null, otherwisefloat64weighted sums.
Remarks
bitwise_and(NDArray, NDArray, NDArray, NDArray, DType)
Compute the bit-wise AND of two arrays element-wise. Only integer and boolean types are handled (NumPy: float/complex inputs raise the no-loop TypeError).
public static NDArray bitwise_and(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayFirst input array.
x2NDArraySecond input array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDType
Returns
- NDArray
Result. This is a scalar if both x1 and x2 are scalars.
Remarks
bitwise_not(NDArray, NDArray, NDArray, DType)
Compute bit-wise inversion, or bit-wise NOT, element-wise. Alias for invert.
public static NDArray bitwise_not(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
- NDArray
Result. This is a scalar if x is a scalar.
Remarks
bitwise_or(NDArray, NDArray, NDArray, NDArray, DType)
Compute the bit-wise OR of two arrays element-wise. Only integer and boolean types are handled (NumPy: float/complex inputs raise the no-loop TypeError).
public static NDArray bitwise_or(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayFirst input array.
x2NDArraySecond input array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDType
Returns
- NDArray
Result. This is a scalar if both x1 and x2 are scalars.
Remarks
bitwise_xor(NDArray, NDArray, NDArray, NDArray, DType)
Compute the bit-wise XOR of two arrays element-wise. Only integer and boolean types are handled (NumPy: float/complex inputs raise the no-loop TypeError).
public static NDArray bitwise_xor(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayFirst input array.
x2NDArraySecond input array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDType
Returns
- NDArray
Result. This is a scalar if both x1 and x2 are scalars.
Remarks
block(object)
Assemble an nd-array from nested lists of blocks.
Blocks in the innermost lists are concatenated (see
concatenate(NDArray[], int?, NDArray, NPTypeCode?, string))
along the last dimension (-1), then these are concatenated along
the second-last dimension (-2), and so on until the outermost
list is reached.
Blocks can be of any dimension, but will not be broadcasted using
the normal rules. Instead, leading axes of size 1 are inserted,
to make block.ndim the same for all blocks.
public static NDArray block(object arrays)
Parameters
arraysobjectNested "lists" of blocks. The C# mapping of NumPy's nested Python lists:
- NDArray — a leaf block.
- numeric scalar (int, double, bool, …) — a 0-d leaf.
- any 1-D Array (
object[],NDArray[],int[], jaggedint[][], …) or non-generic IList (List<T>) — a nested LIST whose elements are classified recursively (mirrors a Python list). - rank ≥ 2 rectangular arrays (
int[,], …) — a leaf, converted via asanyarray(in object, Type). - tuples (ITuple) — rejected with TypeError, matching NumPy ("np.block does not allow implicit conversion from tuple to ndarray").
If passed a single NDArray or scalar (a nested list of depth 0), a copy is returned (matching NumPy 2.x behavior).
Returns
- NDArray
The array assembled from the given blocks. The dimensionality of the output is equal to the greatest of the dimensionality of all the inputs and the depth to which the input list is nested.
Remarks
Exceptions
- ValueError
If list depths are mismatched — for instance
[[a, b], c]is illegal and should be spelt[[a, b], [c]]— or if lists are empty — for instance[[a, b], []].
bmat(NDArray)
Interpret a single array as a matrix — a 2-D copy. A 0-D input becomes (1, 1), a 1-D
input of length N becomes (1, N), and a 2-D input is copied unchanged.
public static NDArray bmat(NDArray obj)
Parameters
objNDArrayInput array.
Returns
- NDArray
A fresh 2-D array holding
obj's values.
Remarks
Port of NumPy 2.x numpy.bmat(ndarray) ≙ matrix(obj), which copies
(matrix's default copy=True) — unlike asmatrix(NDArray, Type),
which returns a view. The copy is taken first, then coerced to 2-D, so the result never
aliases obj. https://numpy.org/doc/stable/reference/generated/numpy.bmat.html
bmat(NDArray[])
Build a 2-D array from a flat sequence of blocks placed side by side: [A, B] joins the
blocks along the last axis, then coerces the result to 2-D.
public static NDArray bmat(NDArray[] obj)
Parameters
objNDArray[]The blocks, concatenated left-to-right (along the last axis).
Returns
- NDArray
The assembled 2-D array.
Remarks
Port of NumPy 2.x numpy.bmat([A, B, …]) ≙ matrix(concatenate(obj, axis=-1)) —
the flat-list branch, equivalent to a single-row [[A, B, …]]. A flat list of 1-D
blocks concatenates to 1-D and is then coerced to a (1, N) row (NumPy's
matrix() finalize). No matrix products; see bmat(NDArray[][]).
https://numpy.org/doc/stable/reference/generated/numpy.bmat.html
bmat(NDArray[][])
Build a 2-D array from a nested sequence of blocks: [[A, B], [C, D]] assembles one
matrix by joining the blocks in each inner list left-to-right and stacking the resulting
rows top-to-bottom.
public static NDArray bmat(NDArray[][] obj)
Parameters
objNDArray[][]Rows of blocks. Each inner array holds the blocks of one row; they are concatenated along the last axis (horizontally). The rows are then concatenated along axis 0 (vertically).
Returns
- NDArray
The assembled 2-D array.
Remarks
Port of NumPy 2.x numpy.bmat ≙ matrix(concatenate([concatenate(row, axis=-1) for
row in obj], axis=0)). It is pure block assembly (concatenation) — it performs NO
matrix multiplication, so no BLAS/OpenBLAS path is involved; the numerics come entirely
from concatenate(NDArray[], int?, NDArray, NPTypeCode?, string) and the 2-D
coercion from asmatrix(NDArray, Type). NumSharp has no dedicated matrix
subclass (NumPy's is pending-deprecated), so the result is a plain 2-D NDArray
— the special matrix operators (* as matmul, ** as matrix power, .H,
.I) are NOT provided. The result dtype follows NumPy's two-stage
result_type(params NDArray[]) promotion (per row, then across rows). Errors reproduce
NumPy's ValueError verbatim (see bmat(ITuple) remarks). See
block(object) for the N-D generalization.
https://numpy.org/doc/stable/reference/generated/numpy.bmat.html
bmat(ITuple)
Build a 2-D array from C# tuples of blocks — (A, B) is a single side-by-side row and
((A, B), (C, D)) is a nested block matrix — the tuple spelling of NumPy's
np.bmat((A, B)) / np.bmat(((A, B), (C, D))).
public static NDArray bmat(ITuple obj)
Parameters
objITupleA ITuple (any
ValueTuple/Tuple): if its first entry is a bare block (NDArray) the whole tuple is one row joined along the last axis; otherwise each entry is a row (itself a tuple /NDArray[]/ sequence of blocks), concatenated per row and stacked along axis 0.
Returns
- NDArray
The assembled 2-D array.
Remarks
Port of NumPy 2.x numpy.bmat's isinstance(obj, (tuple, list)) branch. Mixed
forms work too — ([A, B], [C, D]) (a tuple of lists) — since a row may be a tuple, an
NDArray[], or any IEnumerable of blocks; a non-NDArray
entry is passed through asanyarray(in object, Type) exactly as NumPy runs
asarray over the entries. Still pure concatenation (no matrix products).
Error parity. The errors reproduce numpy.concatenate's contract as
ValueError with NumPy's verbatim text (see BmatConcat(NDArray[], int)): an empty
tuple / row → "need at least one array to concatenate"; a leading 0-D block (a scalar, or a
null — NumPy's None becomes a 0-D array) → "zero-dimensional arrays cannot be
concatenated"; a later block whose rank differs from the first → "all the input arrays must
have same number of dimensions, but the array at index 0 has {n} dimension(s) and the array
at index {k} has {m} dimension(s)". A width/height mismatch between well-ranked blocks keeps
concatenate's IncorrectShapeException — same verbatim NumPy text, the
library-wide house exception type for shape/alignment errors.
https://numpy.org/doc/stable/reference/generated/numpy.bmat.html
bmat(string, IDictionary<string, NDArray>, IDictionary<string, NDArray>)
Build a 2-D array from a matrix string whose tokens name the blocks: rows are separated by
';' and the blocks within a row by commas and/or whitespace, e.g.
"A, B; C, D". Each token is resolved to an NDArray through the supplied
dictionaries (trying ldict first, then gdict); the
blocks of each row are joined along the last axis and the rows are stacked along axis 0.
public static NDArray bmat(string obj, IDictionary<string, NDArray> ldict, IDictionary<string, NDArray> gdict = null)
Parameters
objstringMatrix string such as
"A, B; C, D".ldictIDictionary<string, NDArray>Local name → array map, consulted first (NumPy's
ldict).gdictIDictionary<string, NDArray>Global name → array map, consulted when a name is absent from
ldict(NumPy'sgdict). Optional.
Returns
- NDArray
The assembled 2-D array.
Remarks
Port of NumPy 2.x numpy.bmat(str, ldict, gdict) → matrix(_from_string(...)).
Still pure concatenation (no matrix products).
Divergence — the name dictionary is required. NumPy resolves a bare token against the
CALLER'S Python frame (sys._getframe().f_back) when gdict is None; C#
has no equivalent, so at least one of ldict / gdict
must be supplied (this is the same reason r_/c_ omit the
bmat branch). Resolution tries ldict then
gdict; a token absent from both — including a numeric literal such as
"1", which NumPy also treats as a name — raises NameError
("name '{token}' is not defined"), matching NumPy verbatim. Unlike
asmatrix(string, Type)'s literal parser, brackets are NOT stripped (they
become part of a token and fail to resolve), exactly as NumPy's _from_string leaves
them. https://numpy.org/doc/stable/reference/generated/numpy.bmat.html
Exceptions
- NameError
A token is not present in either dictionary.
broadcast(NDArray, NDArray)
Two-operand overload — the most common case. Retained as an explicit overload so
np.broadcast(a, b) stays binary-compatible and skips the params-array allocation.
public static np.Broadcast broadcast(NDArray nd1, NDArray nd2)
Parameters
Returns
broadcast(params NDArray[])
Produce an object that mimics broadcasting.
public static np.Broadcast broadcast(params NDArray[] arrays)
Parameters
arraysNDArray[]The arrays to broadcast against one another. NumPy caps this at 64 operands (NPY_MAXARGS); NumSharp imposes no cap, matching its unlimited-operand
NDIter.
Returns
- np.Broadcast
Broadcast the input parameters against one another, and return an object that encapsulates the result. Amongst others, it has shape and nd properties, and may be used as an iterator.
Remarks
broadcast_arrays(NDArray, NDArray)
Broadcast two arrays against each other.
public static (NDArray Lhs, NDArray Rhs) broadcast_arrays(NDArray lhs, NDArray rhs)
Parameters
Returns
- (NDArray Lhs, NDArray Rhs)
These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.
Remarks
broadcast_arrays(params NDArray[])
Broadcast any number of arrays against each other.
public static NDArray[] broadcast_arrays(params NDArray[] ndArrays)
Parameters
ndArraysNDArray[]The arrays to broadcast.
Returns
- NDArray[]
These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.
Remarks
broadcast_to(UnmanagedStorage, UnmanagedStorage)
Broadcast an array to a new shape.
public static NDArray broadcast_to(UnmanagedStorage from, UnmanagedStorage against)
Parameters
fromUnmanagedStorageThe UnmanagedStorage to broadcast.
againstUnmanagedStorageThe shape to broadcast against.
Returns
- NDArray
These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.
Remarks
broadcast_to(UnmanagedStorage, NDArray)
Broadcast an array to a new shape.
public static NDArray broadcast_to(UnmanagedStorage from, NDArray against)
Parameters
fromUnmanagedStorageThe UnmanagedStorage to broadcast.
againstNDArrayThe shape to broadcast against.
Returns
- NDArray
These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.
Remarks
broadcast_to(UnmanagedStorage, Shape)
Broadcast an array to a new shape.
public static NDArray broadcast_to(UnmanagedStorage from, Shape against)
Parameters
fromUnmanagedStorageThe NDArray to broadcast.
againstShapeThe shape to broadcast against.
Returns
- NDArray
These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.
Remarks
broadcast_to(NDArray, UnmanagedStorage)
Broadcast an array to a new shape.
public static NDArray broadcast_to(NDArray from, UnmanagedStorage against)
Parameters
fromNDArrayThe NDArray to broadcast.
againstUnmanagedStorageThe shape to broadcast against.
Returns
- NDArray
These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.
Remarks
broadcast_to(NDArray, NDArray)
Broadcast an array to a new shape.
public static NDArray broadcast_to(NDArray from, NDArray against)
Parameters
Returns
- NDArray
These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.
Remarks
broadcast_to(NDArray, Shape)
Broadcast an array to a new shape.
public static NDArray broadcast_to(NDArray from, Shape against)
Parameters
Returns
- NDArray
These arrays are views on the original arrays. They are typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location. If you need to write to the arrays, make copies first.
Remarks
broadcast_to(Shape, UnmanagedStorage)
Broadcast an shape against an other new shape.
public static Shape broadcast_to(Shape from, UnmanagedStorage against)
Parameters
fromShapeThe shape that is to be broadcasted
againstUnmanagedStorageThe shape that'll be used to broadcast
fromshape
Returns
- Shape
A readonly view on the original array with the given shape. It is typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location.
Remarks
broadcast_to(Shape, NDArray)
Broadcast an shape against an other new shape.
public static Shape broadcast_to(Shape from, NDArray against)
Parameters
fromShapeThe shape that is to be broadcasted
againstNDArrayThe shape that'll be used to broadcast
fromshape
Returns
- Shape
A readonly view on the original array with the given shape. It is typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location.
Remarks
broadcast_to(Shape, Shape)
Broadcast an shape against an other new shape.
public static Shape broadcast_to(Shape from, Shape against)
Parameters
fromShapeThe shape that is to be broadcasted
againstShapeThe shape that'll be used to broadcast
fromshape
Returns
- Shape
A readonly view on the original array with the given shape. It is typically not contiguous. Furthermore, more than one element of a broadcasted array may refer to a single memory location.
Remarks
can_cast(DType, DType, NPY_CASTING)
Returns True if cast between data types can occur according to the casting rule (the NPY_CASTING spelling).
public static bool can_cast(DType from, DType to, NPY_CASTING casting)
Parameters
fromDTypetoDTypecastingNPY_CASTING
Returns
can_cast(DType, DType, string)
Returns True if cast between data types can occur according to the casting rule — NumPy's
np.can_cast(from_, to, casting='safe') over two descriptors (PyArray_CanCastTypeTo, NEP 43):
the CastingImpl registered for the two DType CLASSES answers, so byte order and datetime units
take part (can_cast('>i4', 'i4', 'equiv') is True and 'no' is False;
can_cast('M8[D]', 'M8[s]', 'safe') is True and the reverse is False).
public static bool can_cast(DType from, DType to, string casting = "safe")
Parameters
fromDTypeData type to cast from (any spelling that converts to DType).
toDTypeData type to cast to.
castingstringControls what kind of data casting may occur (case-sensitive, as in NumPy):
- "no" means the data types should not be cast at all.
- "equiv" means only byte-order changes are allowed.
- "safe" means only casts which can preserve values are allowed.
- "same_kind" means only safe casts or casts within a kind (int to int, float to float) are allowed.
- "unsafe" means any data conversions may be done.
Returns
- bool
True if cast can occur according to the casting rule.
Remarks
Exceptions
- ValueError
casting must be one of 'no', 'equiv', 'safe', 'same_kind', 'unsafe' (got '…')— verbatim NumPy.
can_cast(NDArray, DType, string)
Returns True if cast from the array's dtype can occur according to the casting rule (NumPy's array form of
can_cast; arrays are never inspected by value under NEP 50).
public static bool can_cast(NDArray from, DType to, string casting = "safe")
Parameters
Returns
can_cast(NDArray, NPTypeCode, string)
Returns True if cast from array dtype can occur according to the casting rule.
public static bool can_cast(NDArray from, NPTypeCode to, string casting = "safe")
Parameters
fromNDArrayArray to cast from.
toNPTypeCodeData type to cast to.
castingstringControls what kind of data casting may occur.
Returns
- bool
True if the array can be cast to the target type.
can_cast(NPTypeCode, NPTypeCode, string)
Returns True if cast between data types can occur according to the casting rule.
public static bool can_cast(NPTypeCode from, NPTypeCode to, string casting = "safe")
Parameters
fromNPTypeCodeData type to cast from.
toNPTypeCodeData type to cast to.
castingstringControls what kind of data casting may occur:
- "no" means the data types should not be cast at all.
- "equiv" means only byte-order changes are allowed.
- "safe" means only casts which can preserve values are allowed.
- "same_kind" means only safe casts or casts within a kind (int to int, float to float) are allowed.
- "unsafe" means any data conversions may be done.
Returns
- bool
True if cast can occur according to the casting rule.
Examples
np.can_cast(NPTypeCode.Int32, NPTypeCode.Int64) // True
np.can_cast(NPTypeCode.Int64, NPTypeCode.Int32) // False
np.can_cast(NPTypeCode.Int32, NPTypeCode.Single, "same_kind") // True (int -> float is allowed)
np.can_cast(NPTypeCode.Int32, NPTypeCode.Int16, "unsafe") // True
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.can_cast.html
The NPTypeCode spelling of can_cast(DType, DType, string): the same NEP 43 engine,
whose answers for the storage-backed types are the rules this overload always applied
(safe ⇔ promote(from, to) == to; same_kind ⇔ safe or the source kind orders at or below the
destination kind).
can_cast(bool, NPTypeCode, string)
Returns True if the bool value can be cast to the data type according to the casting rule.
public static bool can_cast(bool value, NPTypeCode to, string casting = "safe")
Parameters
valuebooltoNPTypeCodecastingstring
Returns
can_cast(byte, NPTypeCode, string)
Returns True if the byte value can be cast to the data type according to the casting rule.
public static bool can_cast(byte value, NPTypeCode to, string casting = "safe")
Parameters
valuebytetoNPTypeCodecastingstring
Returns
can_cast(decimal, NPTypeCode, string)
Returns True if the decimal value can be cast to the data type according to the casting rule.
public static bool can_cast(decimal value, NPTypeCode to, string casting = "safe")
Parameters
valuedecimaltoNPTypeCodecastingstring
Returns
can_cast(double, NPTypeCode, string)
Returns True if the double value can be cast to the data type according to the casting rule.
public static bool can_cast(double value, NPTypeCode to, string casting = "safe")
Parameters
valuedoubletoNPTypeCodecastingstring
Returns
can_cast(short, NPTypeCode, string)
Returns True if the short value can be cast to the data type according to the casting rule.
public static bool can_cast(short value, NPTypeCode to, string casting = "safe")
Parameters
valueshorttoNPTypeCodecastingstring
Returns
can_cast(int, NPTypeCode, string)
Returns True if the int value can be cast to the data type according to the casting rule.
public static bool can_cast(int value, NPTypeCode to, string casting = "safe")
Parameters
valueintInt value to check.
toNPTypeCodeData type to cast to.
castingstringControls what kind of data casting may occur.
Returns
- bool
True if the value can be cast to the target type.
Remarks
NumSharp extension: NumPy 2.x refuses Python scalars here ("can_cast() does not support Python ints, floats, and complex because the result used to depend on the value", NEP 50); NumSharp keeps the value-based answer as a documented convenience.
can_cast(long, NPTypeCode, string)
Returns True if the long value can be cast to the data type according to the casting rule.
public static bool can_cast(long value, NPTypeCode to, string casting = "safe")
Parameters
valuelongtoNPTypeCodecastingstring
Returns
can_cast(object, NPTypeCode, string)
Returns True if the scalar value can be cast to the data type according to the casting rule.
public static bool can_cast(object value, NPTypeCode to, string casting = "safe")
Parameters
valueobjectScalar value to check.
toNPTypeCodeData type to cast to.
castingstringControls what kind of data casting may occur.
Returns
- bool
True if the value can be cast to the target type.
Examples
np.can_cast(100, NPTypeCode.Byte) // True (100 fits in byte)
np.can_cast(1000, NPTypeCode.Byte) // False (1000 > 255)
Remarks
Scalar values can often be cast to smaller types if the value fits (NumSharp extension — see can_cast(int, NPTypeCode, string)).
can_cast(float, NPTypeCode, string)
Returns True if the float value can be cast to the data type according to the casting rule.
public static bool can_cast(float value, NPTypeCode to, string casting = "safe")
Parameters
valuefloattoNPTypeCodecastingstring
Returns
can_cast(string, DType, string)
can_cast(DType, DType, string) for a dtype STRING source (np.can_cast("i4", "i8")). Exists so that a
string first argument binds the dtype grammar rather than NumSharp's string→NDArray (character array) conversion.
public static bool can_cast(string from, DType to, string casting = "safe")
Parameters
Returns
can_cast(Type, Type, string)
Returns True if cast between data types can occur according to the casting rule.
public static bool can_cast(Type from, Type to, string casting = "safe")
Parameters
fromTypeCLR type to cast from.
toTypeCLR type to cast to.
castingstringControls what kind of data casting may occur.
Returns
- bool
True if cast can occur according to the casting rule.
can_cast(ushort, NPTypeCode, string)
Returns True if the ushort value can be cast to the data type according to the casting rule.
public static bool can_cast(ushort value, NPTypeCode to, string casting = "safe")
Parameters
valueushorttoNPTypeCodecastingstring
Returns
can_cast(uint, NPTypeCode, string)
Returns True if the uint value can be cast to the data type according to the casting rule.
public static bool can_cast(uint value, NPTypeCode to, string casting = "safe")
Parameters
valueuinttoNPTypeCodecastingstring
Returns
can_cast(ulong, NPTypeCode, string)
Returns True if the ulong value can be cast to the data type according to the casting rule.
public static bool can_cast(ulong value, NPTypeCode to, string casting = "safe")
Parameters
valueulongtoNPTypeCodecastingstring
Returns
can_cast<TFrom, TTo>(string)
Returns True if cast between data types can occur according to the casting rule.
public static bool can_cast<TFrom, TTo>(string casting = "safe") where TFrom : struct where TTo : struct
Parameters
castingstringControls what kind of data casting may occur.
Returns
- bool
True if cast can occur according to the casting rule.
Type Parameters
TFromSource type.
TToTarget type.
Examples
np.can_cast<int, long>() // True
np.can_cast<long, int>() // False
np.can_cast<int, float>("safe") // True (int to float is safe)
cbrt(NDArray, NDArray, NDArray, DType)
Return the cube-root of an array, element-wise.
public static NDArray cbrt(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayThe values whose cube-roots are required.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of.
Returns
- NDArray
An array of the same shape as x, containing the cube root of each element. If x contains negative values, the result contains the (negative) real cube root. This is a scalar if x is a scalar.
Remarks
ceil(NDArray, NDArray, NDArray, DType)
Return the ceiling of the input, element-wise.
The ceil of the scalar x is the smallest integer i, such that i >= x. It is often denoted as \lceil x \rceil.
public static NDArray ceil(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput data.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of, only non integer values are supported.
Returns
- NDArray
The ceiling of each element in x, with float dtype. This is a scalar if x is a scalar.
Remarks
choose(NDArray, NDArray, NDArray, string)
choose(NDArray, object[], NDArray, string) where choices is a
single array whose OUTERMOST dimension is taken as the sequence (NumPy's "not recommended"
abuse — choices.shape[0] choice sub-arrays). A 0-d choices is a
TypeError ("iteration over a 0-d array"), exactly as NumPy raises.
public static NDArray choose(NDArray a, NDArray choices, NDArray @out = null, string mode = "raise")
Parameters
Returns
choose(NDArray, NDArray[], NDArray, string)
choose(NDArray, object[], NDArray, string) for a strongly-typed array of choices (the common case — every choice is an NDArray). The result dtype is result_type(params object[]) of the choices.
public static NDArray choose(NDArray a, NDArray[] choices, NDArray @out = null, string mode = "raise")
Parameters
Returns
choose(NDArray, object[], NDArray, string)
Construct an array from an index array and a sequence of arrays to choose from. For every
position I of the (broadcast) result, the output is
choices[a[I]][I] — i.e. the value of the a[I]-th choice array at that same
position. a and every choice are first broadcast to a common shape.
public static NDArray choose(NDArray a, object[] choices, NDArray @out = null, string mode = "raise")
Parameters
aNDArrayThe index array. Converted to
int64under the"safe"casting rule (bool and the signed/unsigned integers up touint32are accepted;uint64, float, complex and decimal are rejected with a TypeError).choicesobject[]The choice arrays. Each entry is either an NDArray (strong dtype) or a boxed C# scalar; as in NumPy (NEP50) an
int/float/double/Complex literal is a weak scalar that adopts the other choices' dtype, whilebool,char, Half,decimaland every NDArray are strong. All choices are broadcast against each other and againsta.outNDArrayOptional destination. Its shape must EQUAL the broadcast result shape (not merely broadcast to it); values are cast into it with unsafe casting and the method returns
outitself. Whennull(default) a fresh array is allocated with the choices' common dtype.modestringHow indices outside
[0, n-1]are treated:"raise"(default — throw),"wrap"(modulo with sign correction) or"clip"(values < 0 → 0, values > n-1 → n-1). Case-sensitive, matching NumPy's clip-mode parser.
Returns
- NDArray
A fresh C-contiguous array (or
out) whose dtype is result_type(params object[]) of the choices (NEP50) and whose shape is the broadcast of the choices againsta.
Remarks
Exceptions
- ValueError
choicesis empty ("0-length sequence."), or an index is out of range undermode="raise"("invalid entry in choice array").- TypeError
acannot be safe-cast toint64, orouthas the wrong shape ("choose: invalid shape for output array.").
clip(NDArray, NDArray, NDArray, NDArray, DType, NDArray, NDArray)
Clip (limit) the values in an array.
Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of [0, 1] is specified, values smaller than 0 become 0, and values larger than 1 become 1.
Matches NumPy 2.x signature: clip(a, a_min=None, a_max=None, out=None, *, min=None, max=None). Either or both bounds may be null. The min and max keyword aliases (added in NumPy 2.0) are accepted; mixing a_min with min (or a_max with max) throws.
public static NDArray clip(NDArray a, NDArray a_min = null, NDArray a_max = null, NDArray @out = null, DType dtype = null, NDArray min = null, NDArray max = null)
Parameters
aNDArrayArray containing elements to clip.
a_minNDArrayMinimum value. If null, clipping is not performed on lower interval edge.
a_maxNDArrayMaximum value. If null, clipping is not performed on upper interval edge.
outNDArrayThe results will be placed in this array. It may be the input array for in-place clipping.
outmust be of the right shape to hold the output. Its type is preserved.dtypeDTypeThe dtype the returned ndarray should be of.
minNDArrayNumPy 2.x keyword alias for
a_min. Cannot be combined witha_min.maxNDArrayNumPy 2.x keyword alias for
a_max. Cannot be combined witha_max.
Returns
- NDArray
An array with the elements of a, but where values < min are replaced with min, and those > max with max.
Remarks
column_stack(params NDArray[])
Stack 1-D arrays as columns into a 2-D array. Take a sequence of 1-D arrays and stack them as columns to make a single 2-D array. 2-D arrays are stacked as-is, just like with hstack(params NDArray[]). 1-D arrays are turned into 2-D columns first.
public static NDArray column_stack(params NDArray[] tup)
Parameters
tupNDArray[]Arrays to stack. All of them must have the same first dimension.
Returns
- NDArray
The 2-D array formed by stacking the given arrays.
Remarks
common_type(params NDArray[])
Return a scalar type which is common to the input arrays.
public static DType common_type(params NDArray[] arrays)
Parameters
arraysNDArray[]Input arrays.
Returns
- DType
The common scalar type as CLR Type.
Examples
np.common_type(np.array(new int[] {1, 2})) // typeof(double)
np.common_type(a_float32, a_float64) // typeof(double)
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.common_type.html
The return type will always be a floating-point type (minimum float64 for integers). This differs from result_type which may return an integer type.
common_type_code(params NDArray[])
Return a scalar type code which is common to the input arrays.
public static NPTypeCode common_type_code(params NDArray[] arrays)
Parameters
arraysNDArray[]Input arrays.
Returns
- NPTypeCode
The common scalar type as NPTypeCode.
Remarks
The return type will always be a floating-point type (minimum Double for integers).
common_type_code(params NPTypeCode[])
Return a scalar type code which is common to the input type codes.
public static NPTypeCode common_type_code(params NPTypeCode[] types)
Parameters
typesNPTypeCode[]Input type codes.
Returns
- NPTypeCode
The common scalar type as NPTypeCode.
Remarks
NumPy common_type rules:
- Any Complex input -> Complex (complex128).
- Any Decimal input (NumSharp extension) -> Decimal.
- Any integer/bool/char input -> Double (any int presence forces float64).
- Otherwise (all float16/float32/float64): return max-precision float.
compress(NDArray, NDArray, int?, NDArray)
Return selected slices of a along the given
axis at positions where the 1-D
condition is truthy.
public static NDArray compress(NDArray condition, NDArray a, int? axis = null, NDArray @out = null)
Parameters
conditionNDArray1-D array of booleans (or any dtype interpreted as truthy). Must be 1-D — a 2-D or 0-D condition raises ArgumentException, mirroring NumPy's
ValueError("condition must be a 1-d array"). Iflen(condition) < a.shape[axis], only the firstlen(condition)positions alongaxisare considered; if longer, any True beyonda.shape[axis]raises IndexOutOfRangeException.aNDArraySource array.
axisint?Axis along which to slice.
null(default) flattensafirst.outNDArrayOptional destination. When supplied, shape must match the natural output and
out.dtypemust be safely castable toa.dtype; values are written via copyto(NDArray, NDArray, string, NDArray) with unsafe casting and the method returnsoutitself (matches NumPy's out= dispatch via PyArray_TakeFrom).
Returns
- NDArray
A copy of
awithout the slices alongaxisfor whichconditionis false. Dtype matchesa(orout's dtype when supplied).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.compress.html
Two execution paths:
-
Fast path: bool condition, contig source, no out= or
out= matches src.dtype,
condition.size <= a.shape[axis]. Runs the fused mask-driven gather kernel (popcount → alloc → SIMD bit-scan + cpblk-per-outer-slab), skipping the flatnonzero indices NDArray. -
Generic path: mirrors NumPy's
PyArray_Compresschain — flatnonzero(cond) → take(a, indices, axis, out, "raise"). Handles non-bool conditions, out= with safe dtype cast, and OOB-True via take's RAISE mode.
When condition is 1-D extract(NDArray, NDArray) with
axis = null is equivalent.
concat(NDArray[], int?, NDArray, DType, string)
Join a sequence of arrays along an existing axis. Alias of concatenate(NDArray[], int?, NDArray, NPTypeCode?, string) introduced in NumPy 2.0 for Array API compatibility.
public static NDArray concat(NDArray[] arrays, int? axis = 0, NDArray @out = null, DType dtype = null, string casting = "same_kind")
Parameters
arraysNDArray[]The arrays must have the same shape, except in the dimension corresponding to
axis(the first, by default).axisint?The axis along which the arrays will be joined. If
null, arrays are flattened before use. Default is 0.outNDArrayIf provided, the destination to place the result. Cannot be used together with
dtype.dtypeDTypeIf provided, the result array will have this dtype. Cannot be used together with
out.castingstringControls what kind of data casting may occur. One of
"no","equiv","safe","same_kind"(default), or"unsafe".
Returns
- NDArray
The concatenated array.
Remarks
concat((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concat((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concat((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concat((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concat((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concat((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concat((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concat((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concat((NDArray, NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concat((NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concat((NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concat((NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concat((NDArray, NDArray, NDArray), int)
public static NDArray concat((NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concat((NDArray, NDArray), int)
public static NDArray concat((NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concatenate(NDArray[], int?, NDArray, DType, string)
Join a sequence of arrays along an existing axis.
public static NDArray concatenate(NDArray[] arrays, int? axis = 0, NDArray @out = null, DType dtype = null, string casting = "same_kind")
Parameters
arraysNDArray[]The arrays must have the same shape, except in the dimension corresponding to
axis(the first, by default).axisint?The axis along which the arrays will be joined. If
null, arrays are flattened before use. Default is 0. Negative axes are normalized against the input ndim.outNDArrayIf provided, the destination to place the result. The shape must be correct, matching what would have been returned with no
outargument. Cannot be used together withdtype.dtypeDTypeIf provided, the result array will have this dtype. Cannot be used together with
out.castingstringControls what kind of data casting may occur. One of
"no","equiv","safe","same_kind"(default), or"unsafe".
Returns
- NDArray
The concatenated array.
Remarks
concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concatenate((NDArray, NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concatenate((NDArray, NDArray, NDArray, NDArray), int)
public static NDArray concatenate((NDArray, NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concatenate((NDArray, NDArray, NDArray), int)
public static NDArray concatenate((NDArray, NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
concatenate((NDArray, NDArray), int)
public static NDArray concatenate((NDArray, NDArray) arrays, int axis = 0)
Parameters
Returns
conj(NDArray, NDArray, NDArray, DType)
Alias of conjugate(NDArray, NDArray, NDArray, NPTypeCode?) — return the
complex conjugate, element-wise (NumPy: np.conj is np.conjugate).
public static NDArray conj(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArrayA location into which the result is stored (must be the same shape; returned as-is).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): selects the loop and its output dtype.
Returns
Remarks
conjugate(NDArray, NDArray, NDArray, DType)
Return the complex conjugate, element-wise.
The complex conjugate of a complex number is obtained by changing the sign of its
imaginary part. For real-valued input the conjugate is the value itself.
Mirrors NumPy's ufunc signature conjugate(x, /, out=None, *, where=True, dtype=None).
public static NDArray conjugate(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArrayA location into which the result is stored (must be the same shape; returned as-is).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=). Masked-off slots keep the prior contents of
out.dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): selects the loop and its output dtype.
Returns
- NDArray
The complex conjugate of
x. For real dtypes this is a copy of the input values (dtype preserved) — EXCEPTbool, which NumPy has no loop for and therefore resolves to theint8loop (values 0/1); for Complex the imaginary sign is flipped.
Remarks
convolve(NDArray, 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 static NDArray convolve(NDArray a, NDArray v, string mode = "full")
Parameters
Returns
copy(NDArray, char)
Return an array copy of the given object.
public static NDArray copy(NDArray a, char order = 'K')
Parameters
aNDArrayInput data.
ordercharControls the memory layout of the copy. 'C' - row-major, 'F' - column-major, 'A' - 'F' if source is F-contiguous else 'C', 'K' - match source layout as closely as possible.
Returns
- NDArray
Array interpretation of a.
Remarks
copysign(NDArray, NDArray, NDArray, NDArray, DType)
Change the sign of x1 to that of x2, element-wise.
Returns the magnitude of x1 carrying the sign of x2 (the sign of x2 includes its sign
bit, so copysign(3, -0.0) == -3).
Mirrors NumPy's ufunc signature: copysign(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray copysign(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayValues to change the sign of.
x2NDArrayThe sign of x2 is copied to x1. If shapes differ they must broadcast to a common shape.
outNDArrayA location into which the result is stored (NumPy ufunc out=).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (float-family only).
Returns
- NDArray
The values of x1 with the sign of x2. This is a scalar if both x1 and x2 are scalars.
Remarks
copyto(NDArray, NDArray, string, NDArray)
Copies values from one array to another, broadcasting as necessary.
public static void copyto(NDArray dst, NDArray src, string casting = "same_kind", NDArray where = null)
Parameters
dstNDArrayThe array into which values are copied.
srcNDArrayThe array from which values are copied.
castingstringControls what kind of data casting may occur when copying. Default
"same_kind". Allowed values:"no","equiv","safe","same_kind","unsafe".whereNDArrayOptional boolean mask broadcast to
dst's shape. Elements ofsrcare only written todstwhere the mask istrue.null(default) is equivalent towhere=True— every element is copied.
Remarks
Exceptions
- NumSharpException
If
dstis read-only (NumPy raisesValueError: assignment destination is read-only; the standard write guard — ThrowIfNotWriteable(Shape, string) — is the same one every other write path uses).- ArgumentException
If
castingis not a recognised casting name, orwhereis not a boolean array.- InvalidCastException
If casting from
src's dtype todst's dtype is not allowed under the chosen rule (NumPy raisesTypeError).
corrcoef(NDArray, NDArray, bool, DType)
Return Pearson product-moment correlation coefficients.
The relationship between the correlation coefficient matrix R and the
covariance matrix C (see cov(NDArray, NDArray, bool, bool, int?, NDArray, NDArray, DType)) is
R_ij = C_ij / sqrt(C_ii * C_jj). The values of R are between
-1 and 1, inclusive.
public static NDArray corrcoef(NDArray x, NDArray y = null, bool rowvar = true, DType dtype = null)
Parameters
xNDArrayA 1-D or 2-D array containing multiple variables and observations. Each row of
xrepresents a variable, each column a single observation of all those variables (seerowvar).yNDArrayAn additional set of variables and observations, same shape as
x.rowvarboolIf true (default) each row is a variable with observations in the columns. Otherwise the relationship is transposed: each column is a variable, rows are observations.
dtypeDTypeData-type of the result. By default the result has at least float64 precision.
Returns
- NDArray
The correlation coefficient matrix of the variables.
Remarks
Port of NumPy 2.4.2's numpy/lib/_function_base_impl.corrcoef — a thin wrapper
over cov(NDArray, NDArray, bool, bool, int?, NDArray, NDArray, DType). Like NumPy 2.x this exposes ONLY x/y/rowvar/
dtype; the long-deprecated bias/ddof parameters were removed and are
not offered. All dtype/promotion/edge behaviour is inherited from cov(NDArray, NDArray, bool, bool, int?, NDArray, NDArray, DType), so
the result is bit-identical to NumPy for float64/complex128 (within the managed GEMM's
rounding) and within that GEMM's ULP tolerance for float32/float16 — the same parity
profile as cov(NDArray, NDArray, bool, bool, int?, NDArray, NDArray, DType) itself. Due to floating-point rounding the diagonal may not
be exactly 1 and off-diagonal magnitudes may nudge past 1; the real (and, for complex
input, imaginary) parts are therefore clipped to [-1, 1], exactly as NumPy does.
https://numpy.org/doc/stable/reference/generated/numpy.corrcoef.html
correlate(NDArray, NDArray, string)
Cross-correlation of two 1-dimensional sequences.
c_k = sum_n a_{n+k} * conj(v_n) — the signal-processing convention.
public static NDArray correlate(NDArray a, NDArray v, string mode = "valid")
Parameters
aNDArrayFirst one-dimensional input sequence.
vNDArraySecond one-dimensional input sequence (complex-conjugated internally).
modestring'valid' (default), 'same', or 'full'. Note the default is 'valid', unlike convolve(NDArray, NDArray, string) which defaults to 'full'.
Returns
- NDArray
Discrete cross-correlation of
aandv.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.correlate.html
Port of NumPy 2.4.2's PyArray_Correlate2 + _pyarray_correlate +
small_correlate. correlate is non-commutative: when len(a) < len(v) the
operands are swapped and the output time-reversed, and a complex v is
conjugated — so correlate(v, a) is the time-reversed conjugate of
correlate(a, v).
The output dtype is result_type(a, v). The sliding multiply-accumulate is
outer-vectorized over output positions with SIMD for the 10 Vector<T>-capable
dtypes (byte/sbyte/int/uint families + float32/float64; char via ushort) and scalar for
Half/Complex/Decimal/Boolean, sharing one engine with convolve(NDArray, NDArray, string).
Float bit-parity. Each output accumulates sum_t a[i+t]*k[t] in t-order with
separate multiply-then-add (never FMA), matching NumPy's small_correlate exactly —
so the result is byte-identical to NumPy for the small-kernel regime. For LONG float
kernels NumPy routes the middle/ramps through cblas sdot/ddot (a different
summation order); NumSharp.Core has no BLAS, so those cases carry a bounded-ULP
divergence — a pre-existing property of the scalar sum, NOT introduced by the SIMD path
(the SIMD kernel is bit-identical to the scalar sum for every dtype and size). Integer,
bool, complex, decimal and Half outputs are exact.
cos(NDArray, NDArray, NDArray, DType)
Cosine element-wise.
Mirrors NumPy's ufunc signature: cos(x, /, out=None, *, where=True, dtype=None).
public static NDArray cos(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array in radians.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs at this precision; integer/bool requests raise NumPy's "No loop matching" error.
Returns
- NDArray
The cosine of each element of x. This is a scalar if x is a scalar.
Remarks
cosh(NDArray, NDArray, NDArray, DType)
Hyperbolic cosine, element-wise.
Equivalent to 1/2 * (np.exp(x) + np.exp(-x)) and np.cos(1j* x).
public static NDArray cosh(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of, only non integer values are supported.
Returns
- NDArray
Output array of same shape as x. This is a scalar if x is a scalar.
Remarks
count_nonzero(NDArray)
Counts the number of non-zero values in the array.
public static long count_nonzero(NDArray a)
Parameters
aNDArrayThe array for which to count non-zeros.
Returns
- long
Number of non-zero values in the array.
Remarks
count_nonzero(NDArray, int, bool)
Counts the number of non-zero values in the array along the given axis.
public static NDArray count_nonzero(NDArray a, int axis, bool keepdims = false)
Parameters
aNDArrayThe array for which to count non-zeros.
axisintAxis along which to count non-zeros.
keepdimsboolIf True, the axes which are reduced are left in the result as dimensions with size one.
Returns
- NDArray
Number of non-zero values along the specified axis.
Remarks
cov(NDArray, NDArray, bool, bool, int?, NDArray, NDArray, DType)
Estimate a covariance matrix, given data and weights.
Covariance indicates the level to which two variables vary together. Given
N-dimensional samples X = [x_1, x_2, ..., x_N]^T, the covariance matrix
element C_ij is the covariance of x_i and x_j; C_ii is
the variance of x_i.
public static NDArray cov(NDArray m, NDArray y = null, bool rowvar = true, bool bias = false, int? ddof = null, NDArray fweights = null, NDArray aweights = null, DType dtype = null)
Parameters
mNDArrayA 1-D or 2-D array containing multiple variables and observations. Each row represents a variable, each column a single observation of all those variables (see
rowvar).yNDArrayAn additional set of variables and observations, same form as
m.rowvarboolIf true (default) each row is a variable with observations in the columns. Otherwise the relationship is transposed: each column is a variable, rows are observations.
biasboolDefault normalization (false) is by
(N - 1)(unbiased). If true, normalization is byN. Overridden byddof.ddofint?If not null, overrides the default implied by
bias.ddof=1returns the unbiased estimate even when weights are given;ddof=0returns the simple average.fweightsNDArray1-D array of integer frequency weights (number of times each observation is repeated).
aweightsNDArray1-D array of observation vector weights (relative importance of each observation).
dtypeDTypeData-type of the result. By default the result has at least float64 precision.
Returns
- NDArray
The covariance matrix of the variables.
Remarks
cross(NDArray, NDArray, int, int, int, int?)
Return the cross product of two (arrays of) vectors.
The cross product of a and b in R^3 is a vector
perpendicular to both. Vectors are taken along axisa/axisb
(the last axis by default) and may have length 2 or 3 — where a vector's length is 2 its
missing third component is treated as zero. When BOTH inputs are 2-vectors the scalar
z-component is returned; otherwise the 3-vector result is placed along axisc.
public static NDArray cross(NDArray a, NDArray b, int axisa = -1, int axisb = -1, int axisc = -1, int? axis = null)
Parameters
aNDArrayComponents of the first vector(s).
bNDArrayComponents of the second vector(s).
axisaintAxis of
athat defines the vector(s). By default, the last axis.axisbintAxis of
bthat defines the vector(s). By default, the last axis.axiscintAxis of the result containing the cross product vector(s). Ignored when both inputs are 2-D vectors (the return is then scalar). By default, the last axis.
axisint?If given, the single axis of
a,band the result that defines the vector(s). Overridesaxisa/axisb/axisc.
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.cross.html
A line-for-line port of NumPy's numpy/_core/numeric.py cross: a pure
composition over multiply(NDArray, NDArray, NDArray, NDArray, DType)/negative(NDArray, NDArray, NDArray, DType)/subtract(NDArray, NDArray, NDArray, NDArray, DType)/
moveaxis(NDArray, int, int) (no new kernel), so it supports full broadcasting of the leading
axes and its result dtype is promote_types(a.dtype, b.dtype). The 2-vector forms
are DEPRECATED in NumPy 2.0 but still compute; NumSharp does not model that warning and
simply returns the value. Distinct from cross(NDArray, NDArray, int), the Array-API form,
which accepts 3-vectors only and takes a single axis.
Exceptions
- ValueError
When either input has zero dimensions, or a vector's length is neither 2 nor 3.
- AxisError
When an axis is out of bounds for its operand.
cumprod(NDArray, int?, DType, NDArray)
Return the cumulative product of the elements along a given axis.
public static NDArray cumprod(NDArray arr, int? axis = null, DType typeCode = null, NDArray @out = null)
Parameters
arrNDArrayInput array.
axisint?Axis along which the cumulative product is computed. The default (None) is to compute the cumprod over the flattened array.
typeCodeDTypeType 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.
outNDArrayAlternate output array in which to place the result. It must have the same shape and buffer length as the expected output, but its dtype may differ (the result is cast into it with NumPy's unsafe casting) and a reference to
outis 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(NDArray, int?, DType, NDArray)
Return the cumulative sum of the elements along a given axis.
public static NDArray cumsum(NDArray arr, int? axis = null, DType typeCode = null, NDArray @out = null)
Parameters
arrNDArrayInput array.
axisint?Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array.
typeCodeDTypeType 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.
outNDArrayAlternate output array in which to place the result. It must have the same shape and buffer length as the expected output, but its dtype may differ (the result is cast into it with NumPy's unsafe casting) and a reference to
outis 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
datetime_data(DType)
Get information about the step size of a date or time type — NumPy's np.datetime_data(dtype):
the unit string and the multiplier of a datetime64 / timedelta64 descriptor
(np.datetime_data(np.dtype("M8[10ns]")) == ("ns", 10); a bare M8 is ("generic", 1)).
public static (string unit, int count) datetime_data(DType dtype)
Parameters
dtypeDTypeA datetime64 or timedelta64 descriptor (any spelling that converts to DType, e.g.
"M8[s]").
Returns
Remarks
Exceptions
- TypeError
cannot get datetime metadata from non-datetime type— verbatim NumPy.
deg2rad(NDArray, NDArray, NDArray, DType)
Convert angles from degrees to radians.
public static NDArray deg2rad(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayAngles in degrees.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of.
Returns
- NDArray
The corresponding angle in radians. This is a scalar if x is a scalar.
Remarks
degrees(NDArray, NDArray, NDArray, DType)
Convert angles from radians to degrees. Alias for rad2deg.
public static NDArray degrees(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayAngle in radians.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of.
Returns
- NDArray
The corresponding angle in degrees. This is a scalar if x is a scalar.
Remarks
delete(NDArray, NDArray, int?)
NDArray-typed obj dispatch — selects the integer-array path or the
boolean-mask path based on obj.GetTypeCode. 0-D and 1-element
integer arrays collapse to the scalar-index fast path (matching
NumPy's obj.size == 1 and obj.dtype.kind in "ui": obj = obj.item()).
public static NDArray delete(NDArray arr, NDArray obj, int? axis = null)
Parameters
Returns
delete(NDArray, Slice, int?)
Slice-index overload. obj is interpreted via
Python slice.indices(N) against the axis length.
public static NDArray delete(NDArray arr, Slice obj, int? axis = null)
Parameters
Returns
delete(NDArray, bool[], int?)
Bool-array overload — values are interpreted as a keep-mask
inversion. Length must match the targeted axis size (NumPy raises
ValueError otherwise).
public static NDArray delete(NDArray arr, bool[] obj, int? axis = null)
Parameters
Returns
delete(NDArray, int, int?)
Return a new array with the element at obj
along axis removed.
public static NDArray delete(NDArray arr, int obj, int? axis = null)
Parameters
arrNDArrayInput array.
objintInteger index of the position to remove. Accepts negative indices (counted from the end). Raises IndexOutOfRangeException when out of bounds for the selected axis.
axisint?Axis along which to delete.
null(default) flattensarrfirst and returns a 1-D result.
Returns
- NDArray
A C-contiguous copy of
arrwith one sub-array removed alongaxis.
Remarks
delete(NDArray, int[], int?)
Array-of-indices overload. Negative indices are normalized; duplicates are silently collapsed (each axis position is removed at most once).
public static NDArray delete(NDArray arr, int[] obj, int? axis = null)
Parameters
Returns
delete(NDArray, long, int?)
Long-index overload of delete(NDArray, int, int?).
public static NDArray delete(NDArray arr, long obj, int? axis = null)
Parameters
Returns
delete(NDArray, long[], int?)
Long-array-of-indices overload.
public static NDArray delete(NDArray arr, long[] obj, int? axis = null)
Parameters
Returns
diag(NDArray, int)
Extract a diagonal or construct a diagonal array.
public static NDArray diag(NDArray v, int k = 0)
Parameters
vNDArrayIf
vis 2-D, return a copy of itsk-th diagonal. Ifvis 1-D, return a 2-D array withvon thek-th diagonal.kintDiagonal in question. Use
k > 0for diagonals above the main diagonal, andk < 0for diagonals below the main diagonal.
Returns
- NDArray
The extracted diagonal or constructed diagonal array.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.diag.html
The two branches differ in view-ness, exactly as in NumPy:
the 1-D branch constructs a fresh, writeable, C-contiguous
(n, n) array (n = v.size + |k|); the 2-D branch delegates to
diagonal(NDArray, int, int, int) and therefore returns a read-only view that shares
storage with v — despite the NumPy docstring's talk of "a
copy" (probed against 2.4.2: np.shares_memory is True and
flags.writeable is False).
Exceptions
- ArgumentException
vis not 1- or 2-dimensional —Input must be 1- or 2-d.(NumPy'sValueError).
diag_indices(int, int)
Return the indices to access the main diagonal of an array.
public static NDArray<long>[] diag_indices(int n, int ndim = 2)
Parameters
nintThe size, along each dimension, of the arrays for which the returned indices can be used.
ndimintThe number of dimensions. Default 2.
Returns
- NDArray<long>[]
ndimindex arrays, eacharange(n), suitable for indexing the main diagonal of an array of shape(n,) * ndim.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.diag_indices.html
NumPy's body is idx = np.arange(n); return (idx,) * ndim — the tuple holds
the same array object repeated, so writing through one entry is visible
through all of them (probed against 2.4.2). NumSharp reproduces that aliasing by
returning the identical NDArray<TDType> instance in every slot rather
than ndim independent copies.
A non-positive ndim yields an empty array, mirroring Python's
(idx,) * 0; a negative n yields empty index arrays.
diag_indices_from(NDArray)
Return the indices to access the main diagonal of an n-dimensional array.
public static NDArray<long>[] diag_indices_from(NDArray arr)
Parameters
arrNDArrayArray, at least 2-D, whose dimensions must all be of equal length.
Returns
Remarks
Exceptions
- ArgumentException
input array must be at least 2-dwhenndim < 2, orAll dimensions of input must be of equal lengthwhen the shape is not hyper-cubic (both NumPyValueErrors, verbatim).
diagflat(NDArray, int)
Create a two-dimensional array with the flattened input as a diagonal.
public static NDArray diagflat(NDArray v, int k = 0)
Parameters
vNDArrayInput data, which is flattened (in C order) and set as the
k-th diagonal of the output.kintDiagonal to set; 0, the default, corresponds to the "main" diagonal, a positive (negative)
kgiving the number of the diagonal above (below) the main.
Returns
- NDArray
The 2-D output array of shape
(n, n)wheren = v.size + |k|. Always a freshly allocated, C-contiguous, writeable array.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.diagflat.html
Unlike diag(NDArray, int), diagflat accepts any dimensionality —
the input is raveled first, so a 0-d scalar produces a (1, 1) array and a
3-D input is flattened in C order. Ravel order is logical C order, so an
F-contiguous or strided input is read in row-major index order, not memory order
(probed against NumPy 2.4.2).
diagonal(NDArray, int, int, int)
Return specified diagonals of a. For a 2-D
array, returns the diagonal as a 1-D array. For an N-D array,
the last two axes (default axis1=0,
axis2=1) define the 2-D sub-arrays from which
diagonals are taken; the diagonal is appended as the last axis
of the returned array.
public static NDArray diagonal(NDArray a, int offset = 0, int axis1 = 0, int axis2 = 1)
Parameters
aNDArraySource array. Must have at least 2 dimensions.
offsetintOffset of the diagonal from the main diagonal. Positive values refer to diagonals above the main, negative below. Default 0.
axis1intFirst axis of the 2-D sub-array. Default 0.
axis2intSecond axis of the 2-D sub-array. Default 1.
Returns
- NDArray
A read-only view sharing storage with
a. Shape:a.shapewithaxis1andaxis2removed and the diagonal appended as the last axis.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.diagonal.html
Mirrors NumPy's PyArray_Diagonal (item_selection.c). The
view trick: combining the two strides into one
stride[axis1] + stride[axis2] walks the diagonal in one
step. Read-only by NumPy contract (the writeable-by-default
change pencilled in for NumPy 1.10 hasn't shipped in 2.x).
diff(NDArray, int, int, object, object)
Calculate the n-th discrete difference along the given axis.
The first difference is out[i] = a[i+1] - a[i]; higher
differences are computed recursively.
public static NDArray diff(NDArray a, int n = 1, int axis = -1, object prepend = null, object append = null)
Parameters
aNDArrayInput array (must be at least one dimensional).
nintThe number of times values are differenced. If zero, the input is returned as-is. Must be non-negative.
axisintThe axis along which the difference is taken; default is the last axis. Negative axes count from the end.
prependobjectValue(s) to prepend to
aalongaxisprior to differencing. Scalars expand to length 1 along the axis.nullmeans "not supplied" (NumPy'snp._NoValue).appendobjectValue(s) to append to
aalongaxisprior to differencing. Scalars expand to length 1 along the axis.nullmeans "not supplied".
Returns
- NDArray
The n-th differences. The shape matches the (optionally prepend/append-extended) input except along
axiswhere the size shrinks byn. The dtype is preserved (boolean input yields boolean output via not_equal).
Remarks
digitize(NDArray, NDArray, bool)
Return the indices of the bins to which each value in input array x belongs.
| right | bins order | returned index i satisfies |
|---|---|---|
| false | increasing | bins[i-1] <= x < bins[i] |
| true | increasing | bins[i-1] < x <= bins[i] |
| false | decreasing | bins[i-1] > x >= bins[i] |
| true | decreasing | bins[i-1] >= x > bins[i] |
Values in x beyond the bounds of bins return 0 or
len(bins) as appropriate. Implemented in terms of searchsorted(NDArray, NDArray, string, NDArray).
public static NDArray digitize(NDArray x, NDArray bins, bool right = false)
Parameters
xNDArrayInput array to be binned. May have any shape; the result has the same shape.
binsNDArray1-D monotonic (increasing or decreasing) array of bin edges.
rightboolWhether the intervals include the right or the left bin edge. Default is left-closed (false).
Returns
- NDArray
Array of int64 indices, of the same shape as
x.
Remarks
divide(NDArray, NDArray, NDArray, NDArray, DType)
public static NDArray divide(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
Remarks
dot(NDArray, NDArray, NDArray)
Dot product of two arrays. See remarks.
public static NDArray dot(NDArray a, NDArray b, NDArray @out = null)
Parameters
aNDArrayLhs, First argument.
bNDArrayRhs, Second argument.
outNDArrayOutput argument. Unlike a ufunc's
out,np.dot's is STRICT (itsnew_array_for_sumincommon.c): it must have the EXACT result dtype, the exact number of dimensions, be C-contiguous and writeable — no casting or broadcasting. A dtype / ndim / non-C-array mismatch is"output array is not acceptable (must have the right datatype, number of dimensions, and be a C-Array)"; a same-ndim shape mismatch is"output array has wrong dimensions". Returned as-is when given.
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])
dsplit(NDArray, int)
Split array into multiple sub-arrays along the 3rd axis (depth).
public static NDArray[] dsplit(NDArray ary, int indices_or_sections)
Parameters
aryNDArrayArray to be divided into sub-arrays.
indices_or_sectionsintIf an integer, N, the array will be divided into N equal arrays along axis 2. If such a split is not possible, an error is raised.
Returns
- NDArray[]
A list of sub-arrays as views into ary.
Remarks
Equivalent to split with axis=2. Array must have ndim >= 3. https://numpy.org/doc/stable/reference/generated/numpy.dsplit.html
dsplit(NDArray, int[])
Split array into multiple sub-arrays along the 3rd axis (depth).
public static NDArray[] dsplit(NDArray ary, int[] indices)
Parameters
aryNDArrayArray to be divided into sub-arrays.
indicesint[]A 1-D array of sorted integers indicating where along axis 2 the array is split. For example, [2, 3] would result in ary[:,:,:2], ary[:,:,2:3], ary[:,:,3:].
Returns
- NDArray[]
A list of sub-arrays as views into ary.
Remarks
Equivalent to split with axis=2. Array must have ndim >= 3. https://numpy.org/doc/stable/reference/generated/numpy.dsplit.html
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 static NDArray dstack(params NDArray[] tup)
Parameters
tupNDArray[]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
dtype(DType)
A descriptor converts to itself — np.dtype(np.dtype('f8')).
public static DType dtype(DType dtype)
Parameters
dtypeDType
Returns
dtype(NPTypeCode)
The descriptor of an NPTypeCode — NumSharp's storage enum spelling.
public static DType dtype(NPTypeCode typecode)
Parameters
typecodeNPTypeCode
Returns
dtype(string)
Create a data type object from a NumPy dtype string — the port of descriptor.c's
_convert_from_str (NumPy 2.4.2), the coercion point behind np.dtype('…') and every
dtype= keyword.
public static DType dtype(string dtype)
Parameters
dtypestringAny NumPy-style dtype string: a single type code (
"d","?","q"), a kind plus byte size ("i4","f8","c16","b1"), a name ("float64","intc","longlong","complex128"), a datetime typestr ("M8[ns]","m8","datetime64[10ns]","timedelta64[s/2]"), optionally prefixed with a byte order ("<i4",">f8","=u2","|b1"), or one of NumSharp's PascalCase aliases ("Int32","Single").
Returns
- DType
The matching descriptor: the class's canonical instance for a native builtin (so
np.dtype("i8")is the same object every call), a fresh instance for a non-native byte order (">i4"keepsbyteorder == '>',isnative == false) and for every datetime64/timedelta64 descriptor.
Remarks
Grammar, in NumPy's order: a comma-string / parenthesised sub-array is a structured dtype (unsupported);
the byte-order character is consumed ('|' reads as native, and a lone byte-order character is
invalid); a datetime typestr (M8/m8/datetime64/timedelta64 + metadata) is
parsed by Parse(string); a one-character code is a type code; a code whose tail is
an integer is kind + size (PyArray_TypestrConvert — so "b1" is bool while "b" is
int8, "i3", "f16" and "?1" are invalid); anything else is a NAME looked up in the
type dictionary. Case matters everywhere ("I4" is not "i4"), whitespace is never stripped.
https://numpy.org/doc/stable/reference/arrays.dtypes.html
Exceptions
- ArgumentNullException
dtypeis null.- NotSupportedException
A valid NumPy dtype NumSharp does not implement — bytes/str (S, U, a, c), void, object, complex64, structured / sub-array / comma-string dtypes — or an invalid string, reported with NumPy's own
data type 'X' not understood/Alias 'bool8' was removed in NumPy 2.0. …texts.- TypeError
A malformed datetime unit (
Invalid datetime metadata string "[5]" at position 2, verbatim).- ValueError
A datetime divisor that is not a multiple of a lower unit (verbatim).
dtype(Type)
The descriptor of a C# Type — np.dtype(typeof(int)) (NumPy's np.dtype(np.int32)).
public static DType dtype(Type type)
Parameters
typeType
Returns
ediff1d(NDArray, object, object)
The differences between consecutive elements of an array. The input is flattened first; the result is always 1-D.
public static NDArray ediff1d(NDArray ary, object to_end = null, object to_begin = null)
Parameters
aryNDArrayInput array (flattened before differencing).
to_endobjectNumber(s) to append to the end of the returned differences.
nullmeans none. Cast toary's dtype under thesame_kindcasting rule.to_beginobjectNumber(s) to prepend to the beginning of the returned differences.
nullmeans none. Cast toary's dtype under thesame_kindcasting rule.
Returns
- NDArray
1-D array of consecutive differences (input dtype), optionally bracketed by
to_beginandto_end.
Remarks
einsum(params object[])
Evaluates the Einstein summation convention in NumPy's SUBLIST spelling —
np.einsum(a, [0,1], b, [1,2], [0,2]) — where each operand is followed by its
axis labels as integers, and a trailing list gives the output.
public static NDArray einsum(params object[] operands)
Parameters
operandsobject[]Alternating NDArray and subscript list, optionally closed by a lone output list. A subscript list is an
int[], or anobject[]mixing integers with Ellipsis where NumPy writesEllipsis.
Returns
Remarks
Labels are indices into NumPy's einsum_symbols, UPPER case first: 0-25 are
A-Z and 26-51 are a-z, so [0,1] means "AB" (see the
encoding note on FromSublists(object[], out NDArray[])). Anything outside that range raises
ValueError("subscript is not within the valid range [0, 52)"), and a non-integer
entry raises TypeError("each subscript must be either an integer or an ellipsis")
— both NumPy's, verbatim.
https://numpy.org/doc/stable/reference/generated/numpy.einsum.html
The contraction is a composition over the matrix products — a port of NumPy's
bmm_einsum (its optimize= path) that reduces each pairwise contraction to
matmul(NDArray, NDArray, NDArray, int[][], int?, bool?, DType, string, char), so it runs through OpenBLAS whenever a backend is referenced
(byte-identical to NumPy for float32/float64/complex128) and through the managed GEMM
otherwise. Integer and boolean contractions are byte-exact; a pure float summation done
outside a product (e.g. ij->i, or across three or more operands) can differ in
the last ULP because its accumulation order follows sum(NDArray) and a left-to-right
fold. Every rejection below is unchanged — a malformed expression, a wrong operand
count, a bad ellipsis, an impossible diagonal or a shape conflict is reported the same
way and with the same text as NumPy's default parser.
A single-operand expression that sums nothing away answers with a view of the
operand, exactly as NumPy does: np.einsum("ii->i", a) is a WRITEABLE view of
a's diagonal (writing it writes a), "ij->ji" is the transpose
view, and on this path order= and dtype= are ignored — NumPy's view
attempt wins over both keywords.
One deliberate divergence. NumPy carries TWO independent einsum parsers — the C
one behind the default optimize=False, and a Python one behind the
optimize path — and they word their rejections differently for the same input.
NumSharp reproduces the C one, since that is what a default call hits, and uses it
whatever optimize says. The single exception is a label whose extents disagree
between operands: NumPy's C path leaks its ITERATOR's "remapped shapes" text there,
which describes axis bookkeeping rather than the contraction, so NumSharp raises
NumPy's other wording for the identical error —
Size of label 'j' for operand 1 (3) does not match previous terms (4).
einsum(string, params NDArray[])
Evaluates the Einstein summation convention on the operands.
public static NDArray einsum(string subscripts, params NDArray[] operands)
Parameters
subscriptsstringComma-separated subscript labels, optionally followed by
->and the output labels — e.g."ij,jk->ik". Spaces are ignored and...broadcasts. Without->the output is INFERRED: every label used exactly once, in ASCII order (so an upper-case label sorts before a lower-case one), preceded by the broadcast dimensions.operandsNDArray[]The arrays the subscripts label, in order.
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.einsum.html
The contraction is a composition over the matrix products — a port of NumPy's
bmm_einsum (its optimize= path) that reduces each pairwise contraction to
matmul(NDArray, NDArray, NDArray, int[][], int?, bool?, DType, string, char), so it runs through OpenBLAS whenever a backend is referenced
(byte-identical to NumPy for float32/float64/complex128) and through the managed GEMM
otherwise. Integer and boolean contractions are byte-exact; a pure float summation done
outside a product (e.g. ij->i, or across three or more operands) can differ in
the last ULP because its accumulation order follows sum(NDArray) and a left-to-right
fold. Every rejection below is unchanged — a malformed expression, a wrong operand
count, a bad ellipsis, an impossible diagonal or a shape conflict is reported the same
way and with the same text as NumPy's default parser.
A single-operand expression that sums nothing away answers with a view of the
operand, exactly as NumPy does: np.einsum("ii->i", a) is a WRITEABLE view of
a's diagonal (writing it writes a), "ij->ji" is the transpose
view, and on this path order= and dtype= are ignored — NumPy's view
attempt wins over both keywords.
One deliberate divergence. NumPy carries TWO independent einsum parsers — the C
one behind the default optimize=False, and a Python one behind the
optimize path — and they word their rejections differently for the same input.
NumSharp reproduces the C one, since that is what a default call hits, and uses it
whatever optimize says. The single exception is a label whose extents disagree
between operands: NumPy's C path leaks its ITERATOR's "remapped shapes" text there,
which describes axis bookkeeping rather than the contraction, so NumSharp raises
NumPy's other wording for the identical error —
Size of label 'j' for operand 1 (3) does not match previous terms (4).
Exceptions
- NotSupportedException
Always, once the subscripts validate.
einsum(string, NDArray[], NDArray, DType, char, string, object)
Evaluates the Einstein summation convention, with NumPy's full keyword surface.
public static NDArray einsum(string subscripts, NDArray[] operands, NDArray @out = null, DType dtype = null, char order = 'K', string casting = "safe", object optimize = null)
Parameters
subscriptsstringoperandsNDArray[]outNDArrayWhere the calculation would be deposited. Its RANK is validated now.
dtypeDTypeForces the accumulation dtype.
ordercharMemory layout of the result —
'C','F','A'or'K'.castingstringCasting rule —
"no","equiv","safe","same_kind"or"unsafe".optimizeobjectfalse(the default),true,"greedy"or"optimal". NumPy also takes a precomputed contraction path; that is not modelled, because nothing plans one yet.
Returns
Remarks
Pass the keywords BY NAME — np.einsum("ij->i", ops, @out: dst). They are
keyword-only in NumPy, and naming them is also what keeps them unambiguous here:
NumSharp converts scalars to NDArray implicitly, so a fully positional
einsum(subscripts, ops, null, null, 'K', "safe", true) matches this overload
AND the params one, and the compiler rejects the call as ambiguous.
https://numpy.org/doc/stable/reference/generated/numpy.einsum.html
The contraction is a composition over the matrix products — a port of NumPy's
bmm_einsum (its optimize= path) that reduces each pairwise contraction to
matmul(NDArray, NDArray, NDArray, int[][], int?, bool?, DType, string, char), so it runs through OpenBLAS whenever a backend is referenced
(byte-identical to NumPy for float32/float64/complex128) and through the managed GEMM
otherwise. Integer and boolean contractions are byte-exact; a pure float summation done
outside a product (e.g. ij->i, or across three or more operands) can differ in
the last ULP because its accumulation order follows sum(NDArray) and a left-to-right
fold. Every rejection below is unchanged — a malformed expression, a wrong operand
count, a bad ellipsis, an impossible diagonal or a shape conflict is reported the same
way and with the same text as NumPy's default parser.
A single-operand expression that sums nothing away answers with a view of the
operand, exactly as NumPy does: np.einsum("ii->i", a) is a WRITEABLE view of
a's diagonal (writing it writes a), "ij->ji" is the transpose
view, and on this path order= and dtype= are ignored — NumPy's view
attempt wins over both keywords.
One deliberate divergence. NumPy carries TWO independent einsum parsers — the C
one behind the default optimize=False, and a Python one behind the
optimize path — and they word their rejections differently for the same input.
NumSharp reproduces the C one, since that is what a default call hits, and uses it
whatever optimize says. The single exception is a label whose extents disagree
between operands: NumPy's C path leaks its ITERATOR's "remapped shapes" text there,
which describes axis bookkeeping rather than the contraction, so NumSharp raises
NumPy's other wording for the identical error —
Size of label 'j' for operand 1 (3) does not match previous terms (4).
einsum_path(params object[])
Evaluates the contraction order variadically — np.einsum_path("ij,jk", a, b) — and
in NumPy's SUBLIST spelling — np.einsum_path(a, [0,1], b, [1,2], [0,2]).
Optimization is "greedy"; use the NDArray[] overload to choose a different
optimize.
public static (EinsumPath path, string repr) einsum_path(params object[] operands)
Parameters
operandsobject[]The arrays the subscripts label — only their SHAPES are read.
Returns
- (EinsumPath path, string repr)
The EinsumPath (NumPy's
['einsum_path', …]list) and a printable representation of the path.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.einsum_path.html
A route-for-route port of NumPy 2.4.2's numpy.einsum_path (its greedy/optimal
planner in einsumfunc.py). The EinsumPath and every numeric metric
in the string are byte-identical to NumPy; the only difference is the placeholder letters
an ... expands to in the printed string, which NumPy itself does not pin (they are
drawn from a hash-randomized set and vary per process). NumSharp draws them
deterministically, so the path and the numbers always match.
Spell the operands either as an NDArray[] (this overload) or variadically through
einsum_path(params object[]) — np.einsum_path("ij,jk", a, b). The default
is optimize: "greedy", NumPy's default for einsum_path (note
einsum(string, params NDArray[])'s own default is false).
einsum_path(string, NDArray[])
Evaluates the lowest-cost contraction order for an einsum(string, params NDArray[]) expression, considering the creation of intermediate arrays.
public static (EinsumPath path, string repr) einsum_path(string subscripts, NDArray[] operands)
Parameters
subscriptsstringThe einsum subscripts, e.g.
"ij,jk,kl->il".operandsNDArray[]The arrays the subscripts label — only their SHAPES are read.
Returns
- (EinsumPath path, string repr)
The EinsumPath (NumPy's
['einsum_path', …]list) and a printable representation of the path.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.einsum_path.html
A route-for-route port of NumPy 2.4.2's numpy.einsum_path (its greedy/optimal
planner in einsumfunc.py). The EinsumPath and every numeric metric
in the string are byte-identical to NumPy; the only difference is the placeholder letters
an ... expands to in the printed string, which NumPy itself does not pin (they are
drawn from a hash-randomized set and vary per process). NumSharp draws them
deterministically, so the path and the numbers always match.
Spell the operands either as an NDArray[] (this overload) or variadically through
einsum_path(params object[]) — np.einsum_path("ij,jk", a, b). The default
is optimize: "greedy", NumPy's default for einsum_path (note
einsum(string, params NDArray[])'s own default is false).
einsum_path(string, NDArray[], object)
Evaluates the contraction order, choosing the path type via optimize.
public static (EinsumPath path, string repr) einsum_path(string subscripts, NDArray[] operands, object optimize)
Parameters
subscriptsstringThe einsum subscripts, e.g.
"ij,jk,kl->il".operandsNDArray[]The arrays the subscripts label — only their SHAPES are read.
optimizeobjectfalse/null(no optimization),true(≙"greedy"),"greedy","optimal", a precomputed EinsumPath (an explicit path), or a("greedy"|"optimal", maxIntermediateSize)tuple that caps the largest intermediate. Anything else is rejected exactly as NumPy rejects it.
Returns
- (EinsumPath path, string repr)
The EinsumPath (NumPy's
['einsum_path', …]list) and a printable representation of the path.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.einsum_path.html
A route-for-route port of NumPy 2.4.2's numpy.einsum_path (its greedy/optimal
planner in einsumfunc.py). The EinsumPath and every numeric metric
in the string are byte-identical to NumPy; the only difference is the placeholder letters
an ... expands to in the printed string, which NumPy itself does not pin (they are
drawn from a hash-randomized set and vary per process). NumSharp draws them
deterministically, so the path and the numbers always match.
Spell the operands either as an NDArray[] (this overload) or variadically through
einsum_path(params object[]) — np.einsum_path("ij,jk", a, b). The default
is optimize: "greedy", NumPy's default for einsum_path (note
einsum(string, params NDArray[])'s own default is false).
empty(Shape)
Return a new array of given shape and type, without initializing entries.
public static NDArray empty(Shape shape)
Parameters
shapeShapeShape of the empty array, e.g., (2, 3) or 2.
Returns
- NDArray
Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.
Remarks
empty(Shape, DType, string)
Return a new array of given shape and type, without initializing entries.
public static NDArray empty(Shape shape, DType dtype, string device = null)
Parameters
shapeShapeShape of the empty array, e.g., (2, 3) or 2.
dtypeDTypeDesired output dtype — one descriptor parameter, like NumPy's
dtype: a C# Type, an NPTypeCode, a NumPy dtype string ("f4") or a DType all convert implicitly. Default (null) is numpy.float64.devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity).
Returns
- NDArray
Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.
Remarks
empty(Shape, char, DType)
Return a new array of given shape and type with a specified memory layout.
public static NDArray empty(Shape shape, char order, DType dtype = null)
Parameters
shapeShapeShape of the empty array, e.g., (2, 3) or 2.
ordercharMemory layout: 'C' (row-major), 'F' (column-major), 'A' (any), 'K' (keep). With no source array, 'A' and 'K' default to 'C'.
dtypeDTypeDesired output data-type. Default is numpy.float64.
Returns
- NDArray
Array of uninitialized data with the requested memory layout.
Remarks
empty(int)
Return a new array of given shape and type, without initializing entries.
public static NDArray empty(int shape)
Parameters
shapeint
Returns
- NDArray
Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.
Remarks
empty(int[])
Return a new array of given shape and type, without initializing entries.
public static NDArray empty(int[] shape)
Parameters
shapeint[]Shape of the empty array, e.g., (2, 3) or 2.
Returns
- NDArray
Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.
Remarks
empty(long[])
Return a new array of given shape and type, without initializing entries.
public static NDArray empty(long[] shape)
Parameters
shapelong[]Shape of the empty array, e.g., (2, 3) or 2.
Returns
- NDArray
Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.
Remarks
empty_like(NDArray, DType, Shape, char, string)
Return a new array with the same shape and type as a given array.
public static NDArray empty_like(NDArray prototype, DType dtype, Shape shape, char order, string device = null)
Parameters
prototypeNDArrayThe shape and data-type of prototype define these same attributes of the returned array.
dtypeDTypeOverrides the dtype of the result (a Type, NPTypeCode, dtype string or DType — all convert implicitly).
shapeShapeOverrides the shape of the result.
ordercharMemory layout: 'C', 'F', 'A' or 'K' (default, preserves prototype layout).
devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity).
Returns
- NDArray
Array of uninitialized (arbitrary) data with the same shape and type as prototype.
Remarks
empty_like(NDArray, DType, Shape, string)
Return a new array with the same shape and type as a given array.
public static NDArray empty_like(NDArray prototype, DType dtype = null, Shape shape = default, string device = null)
Parameters
prototypeNDArrayThe shape and data-type of prototype define these same attributes of the returned array.
dtypeDTypeOverrides the dtype of the result — one descriptor parameter, like NumPy's
dtype: a C# Type, an NPTypeCode, a NumPy dtype string ("f4") or a DType all convert implicitly.shapeShapeOverrides the shape of the result.
devicestring
Returns
- NDArray
Array of uninitialized (arbitrary) data with the same shape and type as prototype.
Remarks
empty<T>(int[])
Return a new array of given shape and type, without initializing entries.
public static NDArray empty<T>(int[] shape)
Parameters
shapeint[]Shape of the empty array, e.g., (2, 3) or 2.
Returns
- NDArray
Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.
Type Parameters
T
Remarks
empty<T>(long[])
Return a new array of given shape and type, without initializing entries.
public static NDArray empty<T>(long[] shape)
Parameters
shapelong[]Shape of the empty array, e.g., (2, 3) or 2.
Returns
- NDArray
Array of uninitialized (arbitrary) data of the given shape, dtype, and order. Object arrays will be initialized to None.
Type Parameters
T
Remarks
equal(NDArray, NDArray, NDArray, NDArray, DType)
Return (x1 == x2) element-wise.
Mirrors NumPy's ufunc signature: equal(x1, x2, /, out=None, *, where=True, dtype=None).
A plain call returns a bool-dtype array (the instance is an NDArray<TDType> of bool —
cast or use the == operator for the typed wrapper).
public static NDArray equal(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayInput array.
x2NDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): comparisons have bool loops only — any non-bool request raises the no-loop TypeError.
Returns
Remarks
equal(NDArray, object)
Return (x1 == x2) element-wise with scalar.
public static NDArray<bool> equal(NDArray x1, object x2)
Parameters
Returns
equal(object, NDArray)
Return (x1 == x2) element-wise with scalar on left.
public static NDArray<bool> equal(object x1, NDArray x2)
Parameters
Returns
evaluate(NDExpr, NDArray)
Evaluate an expression tree over NDArrays in ONE fused pass — no intermediate arrays, one read of each operand, one write of the result (NumSharp extension; the NumPy-ecosystem equivalent is numexpr.evaluate).
public static NDArray evaluate(NDExpr expr, NDArray @out = null)
Parameters
exprNDExprExpression with embedded array leaves. NDArrays convert implicitly, so one cast lights up the whole operator set:
NDArray r = np.evaluate((NDExpr)a * b + 2); // a*b+2 fused NDArray d = np.evaluate((NDExpr.Arr(a) - b) / (NDExpr.Arr(a) + b)); NDArray s = np.evaluate(NDExpr.Sum((NDExpr)a * b)); // one-pass sum(a*b)A repeated NDArray reference becomes ONE iterator operand.
outNDArrayOptional pre-allocated result (ufunc out= rules: joins the broadcast but is never stretched; same_kind cast from the resolved dtype; may alias an input — overlap-safe).
Returns
- NDArray
The evaluated array at the tree's NumPy result_type — dtypes match the equivalent unfused NumPy expression node-for-node (NEP50, including weak python-scalar literals). Root reductions (Sum(NDExpr) / Prod / Min / Max / Mean) return a 0-d scalar array.
evaluate(NDExpr, NDArray[], NDArray)
Evaluate an expression built over positional
Input(int) leaves against an explicit operand
list: np.evaluate(NDExpr.Input(0) * NDExpr.Input(1), new[] { a, b }).
public static NDArray evaluate(NDExpr expr, NDArray[] operands, NDArray @out = null)
Parameters
Returns
exp(NDArray)
Base-e exponential, element-wise.
public static NDArray exp(NDArray a)
Parameters
aNDArrayInput value.
Returns
- NDArray
The natural logarithm of x, element-wise. This is a scalar NDArray.
Remarks
exp(NDArray, NDArray, NDArray, DType)
Calculate the exponential of all elements in the input array.
Mirrors NumPy's ufunc signature: exp(x, /, out=None, *, where=True, dtype=None).
public static NDArray exp(NDArray a, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
aNDArrayInput value.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs at this precision; integer/bool requests raise NumPy's "No loop matching" error.
Returns
Remarks
exp2(NDArray)
Calculate 2**p for all p in the input array.
public static NDArray exp2(NDArray a)
Parameters
aNDArrayInput value.
Returns
- NDArray
Element-wise 2 to the power x. This is a scalar if x is a scalar.
Remarks
exp2(NDArray, NDArray, NDArray, DType)
Mirrors NumPy's ufunc signature: exp2(x, /, out=None, *, where=True, dtype=None).
public static NDArray exp2(NDArray a, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
aNDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): selects the loop; the input must be same_kind-castable to it.
Returns
Remarks
expand_dims(NDArray, IEnumerable<int>)
Sequence overload — accepts any IEnumerable<T>, materializes to an array, and delegates to the tuple-axis path.
public static NDArray expand_dims(NDArray a, IEnumerable<int> axis)
Parameters
aNDArrayaxisIEnumerable<int>
Returns
expand_dims(NDArray, int)
public static NDArray expand_dims(NDArray a, int axis)
Parameters
Returns
expand_dims(NDArray, int[])
Expand the shape of an array. Insert new axes that will appear at
the axis positions in the expanded output.
public static NDArray expand_dims(NDArray a, int[] axis)
Parameters
Returns
Remarks
Matches NumPy 2.x: each axis in the tuple is normalized against
the FINAL output ndim (a.ndim + axis.Length). Duplicate
normalized positions raise ArgumentException
("repeated axis"); out-of-range axes throw the same.
Empty axis returns the input unchanged.
expm1(NDArray)
Calculate exp(x) - 1 for all elements in the array.
public static NDArray expm1(NDArray a)
Parameters
aNDArrayInput value.
Returns
- NDArray
Element-wise exponential minus one: out = exp(x) - 1. This is a scalar if x is a scalar.
Remarks
expm1(NDArray, NDArray, NDArray, DType)
Mirrors NumPy's ufunc signature: expm1(x, /, out=None, *, where=True, dtype=None).
public static NDArray expm1(NDArray a, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
aNDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): selects the loop; the input must be same_kind-castable to it.
Returns
Remarks
extract(NDArray, NDArray)
Return the elements of arr that satisfy some
condition. Equivalent to
np.take(np.ravel(arr), np.flatnonzero(np.ravel(condition))) —
i.e. arr.ravel()[condition.ravel()] when condition is boolean.
public static NDArray extract(NDArray condition, NDArray arr)
Parameters
conditionNDArrayArray whose nonzero / True entries indicate the elements of
arrto extract. May be any dtype (treated as truthy via NumPy's "nonzero" semantics). May be any shape — it is ravel'd before alignment witharr.arrNDArrayInput array. May be any shape; it is ravel'd.
Returns
- NDArray
Rank-1 NDArray of values from
arrwhere the corresponding ravel'dconditionentry is truthy. Dtype matchesarr.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.extract.html
Two execution paths:
-
Fast path: bool condition, contig arr + condition,
condition.size <= arr.size. Runs a fused IL kernel (popcount → alloc → SIMD bit-scan + cpblk) avoiding the indices NDArray allocation that the generic path needs. -
Generic path: mirrors NumPy's literal chain
take(ravel(arr), flatnonzero(ravel(condition))). Handles non-bool conditions (any dtype interpreted as nonzero), broadcast / strided / negative-stride sources, and the OOB-True case (raises via take's RAISE mode).
Note that place(NDArray, NDArray, NDArray) is the inverse operation.
eye(int, int?, int, DType, char, string)
Return a 2-D array with ones on the diagonal and zeros elsewhere.
public static NDArray eye(int N, int? M = null, int k = 0, DType dtype = null, char order = 'C', string device = null)
Parameters
NintNumber of rows in the output.
Mint?Number of columns in the output. If None, defaults to N.
kintIndex of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal.
dtypeDTypeData-type of the returned array.
ordercharMemory layout: 'C' (row-major, default) or 'F' (column-major).
devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity).
Returns
- NDArray
An array where all elements are equal to zero, except for the k-th diagonal, whose values are equal to one.
Remarks
fill_diagonal(NDArray, object, bool)
Fill the main diagonal of the given array of any dimensionality — in place.
public static void fill_diagonal(NDArray a, object val, bool wrap = false)
Parameters
aNDArrayArray whose diagonal is to be filled; it is modified in place.
valobjectValue(s) to write into the diagonal. A scalar is repeated; a sequence is raveled and then tiled cyclically (and truncated) to the diagonal's length.
wrapboolFor tall matrices the diagonal "wraps" after N columns and continues on the row below. Off by default.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.fill_diagonal.html
Values tile, they do not broadcast. NumPy's body ends in
a.flat[:end:step] = val, and flat-iterator assignment repeats a short
right-hand side rather than raising: probed on a 6×6, [1,2,3,4] fills the
diagonal as [1,2,3,4,1,2], while an over-long value list is truncated and
an empty one is a silent no-op. resize(NDArray,int[]) already
implements exactly that cyclic-tile-or-truncate rule, so it supplies the values.
No element loop. NumPy addresses the diagonal as a strided slice of the
flat iterator; NumSharp resolves the same positions into real strides and
writes through ordinary aliased views. Without wrapping the targets are
(i, i, …, i), i.e. one constant stride of Σ strides — a single view.
With wrapping on a tall matrix the flat position of target i = q·cols + r
is q·(cols+1)·s0 + r·(s0+s1), so the run splits into ceil(count/cols)
equally-strided blocks — a handful of views, still no per-element addressing.
Because the targets are computed from strides rather than from memory order, this
works unchanged on transposed, sliced and otherwise non-contiguous arrays, which
it writes through exactly as NumPy does.
Exceptions
- ArgumentException
array must be at least 2-d,All dimensions of input must be of equal length(ndim > 2 with a non-hyper-cubic shape), orunderlying array is read-only— all verbatim NumPyValueErrortexts.
find_common_type(DType[])
Determine common type following standard coercion rules — the DType form, which is what the
np.float32/np.int64 spellings are (new[] { np.float32, np.int64 } is a DType[]).
public static DType find_common_type(DType[] array_types)
Parameters
array_typesDType[]A list of dtype descriptors representing arrays. Can be null.
Returns
- DType
The common data type of
array_types(no scalar types).
Remarks
find_common_type(DType[], DType[])
Determine common type following standard coercion rules — the DType form, which is what the
np.float32/np.int64 spellings are (new[] { np.float32, np.int64 } is a DType[]).
public static DType find_common_type(DType[] array_types, DType[] scalar_types)
Parameters
array_typesDType[]A list of dtype descriptors representing arrays. Can be null.
scalar_typesDType[]A list of dtype descriptors representing scalars. Can be null.
Returns
- DType
The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned.
Remarks
find_common_type(NPTypeCode[], NPTypeCode[])
Determine common type following standard coercion rules.
public static DType find_common_type(NPTypeCode[] array_types, NPTypeCode[] scalar_types)
Parameters
array_typesNPTypeCode[]A list of dtypes or dtype convertible objects representing arrays. Can be null.
scalar_typesNPTypeCode[]A list of dtypes or dtype convertible objects representing scalars.Can be null.
Returns
- DType
The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned.
Remarks
find_common_type(NPTypeCode[], Type[])
Determine common type following standard coercion rules.
public static DType find_common_type(NPTypeCode[] array_types, Type[] scalar_types)
Parameters
array_typesNPTypeCode[]A list of dtypes or dtype convertible objects representing arrays. Can be null.
scalar_typesType[]A list of dtypes or dtype convertible objects representing scalars.Can be null.
Returns
- DType
The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned.
Remarks
find_common_type(params string[])
Resolves to which type should the output be.
public static DType find_common_type(params string[] involvedTypes)
Parameters
involvedTypesstring[]
Returns
find_common_type(string[], string[])
Determine common type following standard coercion rules.
public static DType find_common_type(string[] array_types, string[] scalar_types)
Parameters
array_typesstring[]A list of dtypes or dtype convertible objects representing arrays. Can be null.
scalar_typesstring[]A list of dtypes or dtype convertible objects representing scalars.Can be null.
Returns
- DType
The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned.
Remarks
find_common_type(Type[])
Determine common type following standard coercion rules.
public static DType find_common_type(Type[] array_types)
Parameters
array_typesType[]A list of dtypes or dtype convertible objects representing arrays. Can be null.
Returns
- DType
The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned.
Remarks
find_common_type(Type[], NPTypeCode[])
Determine common type following standard coercion rules.
public static DType find_common_type(Type[] array_types, NPTypeCode[] scalar_types)
Parameters
array_typesType[]A list of dtypes or dtype convertible objects representing arrays. Can be null.
scalar_typesNPTypeCode[]A list of dtypes or dtype convertible objects representing scalars.Can be null.
Returns
- DType
The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned.
Remarks
find_common_type(Type[], Type[])
Determine common type following standard coercion rules.
public static DType find_common_type(Type[] array_types, Type[] scalar_types)
Parameters
array_typesType[]A list of dtypes or dtype convertible objects representing arrays. Can be null.
scalar_typesType[]A list of dtypes or dtype convertible objects representing scalars.Can be null.
Returns
- DType
The common data type, which is the maximum of array_types ignoring scalar_types, unless the maximum of scalar_types is of a different kind (dtype.kind). If the kind is not understood, then None is returned.
Remarks
finfo(DType)
Machine limits for floating point types.
public static finfo finfo(DType dtype)
Parameters
dtypeDTypeThe floating point dtype — one descriptor parameter, like NumPy's: a C# Type (
typeof(double)), an NPTypeCode, a NumPy dtype string or a DType (np.float64,arr.dtype) all convert implicitly.
Returns
- finfo
An finfo object describing the floating point type limits.
Examples
var info = np.finfo(np.float64);
Console.WriteLine(info.bits); // 64
Console.WriteLine(info.eps); // ~2.22e-16
Console.WriteLine(info.precision); // 15
Remarks
finfo(NDArray)
Machine limits for floating point types.
public static finfo finfo(NDArray arr)
Parameters
arrNDArrayAn NDArray with floating point dtype.
Returns
- finfo
An finfo object describing the array's floating point type limits.
Examples
var a = np.array(new double[] {1.0, 2.0, 3.0});
var info = np.finfo(a);
Console.WriteLine(info.bits); // 64
Exceptions
- ArgumentNullException
Thrown if arr is null.
finfo(string)
Machine limits for floating point types.
public static finfo finfo(string dtypeName)
Parameters
dtypeNamestringA dtype string (e.g., "float32", "float64", "double").
Returns
- finfo
An finfo object describing the floating point type limits.
Examples
var info = np.finfo("float64");
Console.WriteLine(info.bits); // 64
Exceptions
- ArgumentException
Thrown if dtypeName is not a valid floating point dtype.
finfo<T>()
Machine limits for floating point types.
public static finfo finfo<T>() where T : struct
Returns
- finfo
An finfo object describing the floating point type limits.
Type Parameters
TA floating point type (float, double, decimal).
Examples
var info = np.finfo<double>();
Console.WriteLine(info.bits); // 64
flat(NDArray)
Build a np.FlatIterator over a — the write-through,
C-order flat iterator that is the analog of NumPy's flatiter
(a.flat's type). NumSharp's flat property already returns
a raveled NDArray and is deeply embedded, so it cannot be reclaimed to
return this type; the flat iterator lives on the flatiter accessor
(and this factory) instead.
public static np.FlatIterator flat(NDArray a)
Parameters
aNDArray
Returns
Remarks
flat<T>(NDArray, bool)
Typed, allocation-free FLAT iteration — the unboxed, by-reference counterpart of
flat(NDArray) / flatiter. Yields ref T
straight into the array's memory in logical C-order (last axis fastest,
honouring the array's strides — the same order the boxed np.FlatIterator
walks), so reading costs a dereference and writing goes through to the array for
EVERY memory layout — transposed, sliced, strided, negative-stride, broadcast.
var a = np.arange(6).reshape(2, 3).T; // transposed (non-contiguous) view
// read, by reference, in C-order (0 3 1 4 2 5 — same as a.flatiter)
double total = 0;
foreach (ref double x in np.flat<double>(a))
total += x;
// write through, in C-order
foreach (ref double x in np.flat<double>(a, writeable: true))
x *= 2;
public static np.FlatRefIter<T> flat<T>(NDArray a, bool writeable = false) where T : unmanaged
Parameters
aNDArrayThe array to iterate over.
writeableboolOpen the operand
readwriteso assignments through therefreach the array. A read-only broadcast view (stride-0) is rejected with NumPy's verbatim message. (Likenp.nditer<T>, this is a caller contract, not a C# read-only guarantee — the iterator is never buffered, so assigning through therefalways writes physically.)
Returns
- np.FlatRefIter<T>
Type Parameters
TMust be EXACTLY the array's element type — no conversion or casting is performed, because a
refcannot convert. A mismatch throws rather than reinterpreting the bytes (cast first witha.astype(...)). This is why the typed form cannot do the NumPy-style scalar coercion the boxed np.FlatIterator's setters do.
Remarks
NumSharp extension: NumPy's flatiter hands back a boxed scalar per element
because Python has no unboxed generics. This is the same walk with the boxing and the
per-element view removed. It is exactly np.nditer<T>(a, order: 'C') with a
C-order default baked in to match flatiter's order (the
order-configurable nditer<T>(NDArray, bool, char) defaults instead to
memory order 'K'); it runs on the very same NDIterRef engine.
Empty arrays iterate zero times and a 0-d array yields its single element
— matching the boxed np.FlatIterator, and unlike the boxed np.nditer
which requires the zerosize_ok flag for an empty operand.
flatnonzero(NDArray)
Return indices that are non-zero in the flattened version of a.
This is equivalent to np.nonzero(np.ravel(a))[0].
public static NDArray<long> flatnonzero(NDArray a)
Parameters
aNDArrayInput data.
Returns
- NDArray<long>
1-D NDArray<TDType> of long (NumPy
intp) containing the indices of elements ofa.ravel()that are non-zero. For 0-d input, returns[0]when the value is truthy and an empty array otherwise. For empty input, returns an empty 1-D array.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.flatnonzero.html
Faster than the literal composition nonzero(ravel(a))[0]: the engine
runs the SIMD popcount + bit-scan straight into the 1-D result buffer
without materializing the per-axis coordinate arrays produced by
nonzero(NDArray). For multi-dim inputs the cost is the same as a 1-D
input of equal element count (the layout is collapsed by materializing to
C-contig when needed).
flip(NDArray, int[])
Reverse the order of elements in an array along the given axes. The shape of the array is preserved, but the elements are reordered.
public static NDArray flip(NDArray m, int[] axis)
Parameters
mNDArrayInput array.
axisint[]Axes along which to flip over — NumPy's tuple-of-ints form; flipping is performed on all of the specified axes. Negative axes count from the last to the first axis. An empty array flips no axis (returns an unreversed view of the whole array); null flips all axes.
Returns
- NDArray
A view of
mwith the entries of the given axes reversed. Since a view is returned, this operation is done in constant time.
Remarks
Exceptions
- AxisError
When any axis is out of bounds for the array's dimensions.
- ValueError
When an axis is repeated ("repeated axis").
flip(NDArray, int?)
Reverse the order of elements in an array along the given axis. The shape of the array is preserved, but the elements are reordered.
public static NDArray flip(NDArray m, int? axis = null)
Parameters
mNDArrayInput array.
axisint?Axis along which to flip over. The default, null, will flip over all of the axes of the input array. If axis is negative it counts from the last to the first axis.
Returns
- NDArray
A view of
mwith the entries of axis reversed. Since a view is returned, this operation is done in constant time.
Remarks
Exceptions
- AxisError
When
axisis out of bounds for the array's dimensions.
fliplr(NDArray)
Reverse the order of elements along axis 1 (left/right). For a 2-D array, this flips the entries in each row in the left/right direction. Columns are preserved, but appear in a different order than before.
public static NDArray fliplr(NDArray m)
Parameters
mNDArrayInput array, must be at least 2-D.
Returns
- NDArray
A view of
mwith the columns reversed — equivalent to m[:, ::-1] or np.flip(m, axis: 1). Since a view is returned, this operation is done in constant time.
Remarks
Exceptions
- ValueError
When
mis less than 2-d ("Input must be >= 2-d.").
flipud(NDArray)
Reverse the order of elements along axis 0 (up/down). For a 2-D array, this flips the entries in each column in the up/down direction. Rows are preserved, but appear in a different order than before.
public static NDArray flipud(NDArray m)
Parameters
mNDArrayInput array, must be at least 1-D.
Returns
- NDArray
A view of
mwith the rows reversed — equivalent to m[::-1, ...] or np.flip(m, axis: 0). Since a view is returned, this operation is done in constant time.
Remarks
Exceptions
- ValueError
When
mis less than 1-d ("Input must be >= 1-d.").
floor(NDArray, NDArray, NDArray, DType)
public static NDArray floor(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
floor_divide(NDArray, NDArray, NDArray, NDArray, DType)
Return the largest integer smaller or equal to the division of the inputs.
It is equivalent to the Python // operator.
Mirrors NumPy's ufunc signature: floor_divide(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray floor_divide(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayDividend array.
x2NDArrayDivisor array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs in this dtype; inputs must be same_kind-castable to it.
Returns
- NDArray
y = floor(x1/x2). This is a scalar if both x1 and x2 are scalars.
Remarks
floor_divide(NDArray, object)
Return the largest integer smaller or equal to the division of the inputs. Scalar or array-like divisor version.
public static NDArray floor_divide(NDArray x1, object x2)
Parameters
Returns
- NDArray
y = floor(x1/x2).
fmax(NDArray, NDArray, DType)
Element-wise maximum of array elements, ignoring NaNs. Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then the non-nan element is returned. If both elements are NaNs then the first is returned. The net effect is that NaNs are ignored when possible.
public static NDArray fmax(NDArray x1, NDArray x2, DType dtype = null)
Parameters
x1NDArrayThe arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
x2NDArrayThe arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
dtypeDTypeLoop dtype (NumPy ufunc dtype=): the comparison runs at this precision.
Returns
- NDArray
The maximum of x1 and x2, element-wise, ignoring NaNs.
fmax(NDArray, NDArray, NDArray)
Element-wise maximum of array elements, ignoring NaNs, writing into @out.
public static NDArray fmax(NDArray x1, NDArray x2, NDArray @out)
Parameters
Returns
fmin(NDArray, NDArray, DType)
Element-wise minimum of array elements, ignoring NaNs. Compare two arrays and returns a new array containing the element-wise minima. If one of the elements being compared is a NaN, then the non-nan element is returned. If both elements are NaNs then the first is returned. The net effect is that NaNs are ignored when possible.
public static NDArray fmin(NDArray x1, NDArray x2, DType dtype = null)
Parameters
x1NDArrayThe arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
x2NDArrayThe arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
dtypeDTypeLoop dtype (NumPy ufunc dtype=): the comparison runs at this precision.
Returns
- NDArray
The minimum of x1 and x2, element-wise, ignoring NaNs.
fmin(NDArray, NDArray, NDArray)
Element-wise minimum of array elements, ignoring NaNs, writing into @out.
public static NDArray fmin(NDArray x1, NDArray x2, NDArray @out)
Parameters
Returns
format_float_positional(double, int?, bool, bool, char, bool, int?, int?, int?)
Format a floating-point scalar as a decimal string in positional notation
(NumPy's np.format_float_positional).
public static string format_float_positional(double x, int? precision = null, bool unique = true, bool fractional = true, char trim = 'k', bool sign = false, int? pad_left = null, int? pad_right = null, int? min_digits = null)
Parameters
xdoubleprecisionint?uniqueboolfractionalbooltrimcharsignboolpad_leftint?pad_rightint?min_digitsint?
Returns
format_float_scientific(double, int?, bool, char, bool, int?, int?, int?)
Format a floating-point scalar as a decimal string in scientific notation
(NumPy's np.format_float_scientific).
public static string format_float_scientific(double x, int? precision = null, bool unique = true, char trim = 'k', bool sign = false, int? pad_left = null, int? exp_digits = null, int? min_digits = null)
Parameters
xdoubleprecisionint?uniquebooltrimcharsignboolpad_leftint?exp_digitsint?min_digitsint?
Returns
frombuffer(MemoryView, DType, long, long)
Interpret a np.MemoryView (obtained from data) as a
1-dimensional array, sharing its memory (zero-copy) — the consumer side of ndarray.data.
public static NDArray frombuffer(np.MemoryView buffer, DType dtype = null, long count = -1, long offset = 0)
Parameters
buffernp.MemoryViewA np.MemoryView over a C-contiguous array.
dtypeDTypeData-type of the returned array. Default is float64.
countlongNumber of items to read. -1 means all data in the buffer.
offsetlongStart reading the buffer from this offset (in bytes). Default is 0.
Returns
Remarks
frombuffer(MemoryView, NPTypeCode, long, long)
Interpret a np.MemoryView (obtained from data) as a
1-dimensional array, sharing its memory (zero-copy) — the consumer side of ndarray.data.
public static NDArray frombuffer(np.MemoryView buffer, NPTypeCode dtype, long count = -1, long offset = 0)
Parameters
buffernp.MemoryViewA np.MemoryView over a C-contiguous array.
dtypeNPTypeCodeData-type of the returned array. Default is float64.
countlongNumber of items to read. -1 means all data in the buffer.
offsetlongStart reading the buffer from this offset (in bytes). Default is 0.
Returns
Remarks
frombuffer(MemoryView, string, long, long)
Interpret a np.MemoryView as a 1-dimensional array, given a dtype STRING
(e.g. "<i4", ">u4" for big-endian uint32). Little-endian / native dtypes are
a zero-copy view; a big-endian dtype needs a byte-swap and so COPIES (as the byte[] path does).
public static NDArray frombuffer(np.MemoryView buffer, string dtype, long count = -1, long offset = 0)
Parameters
buffernp.MemoryViewA np.MemoryView over a C-contiguous array.
dtypestringData-type of the returned array. Default is float64.
countlongNumber of items to read. -1 means all data in the buffer.
offsetlongStart reading the buffer from this offset (in bytes). Default is 0.
Returns
Remarks
frombuffer(ArraySegment<byte>, DType, long)
Interpret an ArraySegment as a 1-dimensional array. Uses the segment's Offset and Count automatically.
public static NDArray frombuffer(ArraySegment<byte> segment, DType dtype = null, long count = -1)
Parameters
segmentArraySegment<byte>The array segment to interpret.
dtypeDTypeData-type of the returned array. Default is float64.
countlongNumber of items to read. -1 means all data in the segment.
Returns
- NDArray
1-dimensional NDArray viewing the segment's data.
frombuffer(ArraySegment<byte>, NPTypeCode, long)
Interpret an ArraySegment as a 1-dimensional array.
public static NDArray frombuffer(ArraySegment<byte> segment, NPTypeCode dtype, long count = -1)
Parameters
segmentArraySegment<byte>dtypeNPTypeCodecountlong
Returns
frombuffer(byte[], DType, long, long)
Interpret a buffer as a 1-dimensional array.
public static NDArray frombuffer(byte[] buffer, DType dtype = null, long count = -1, long offset = 0)
Parameters
bufferbyte[]An object that exposes the buffer interface.
dtypeDTypeData-type of the returned array. Default is float64.
countlongNumber of items to read. -1 means all data in the buffer.
offsetlongStart reading the buffer from this offset (in bytes). Default is 0.
Returns
- NDArray
1-dimensional NDArray with data interpreted from the buffer.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.frombuffer.html
Like NumPy, this creates a VIEW of the buffer (pins the array, shares memory). Modifications to the NDArray will affect the original buffer. The buffer must stay alive while the NDArray is in use.
frombuffer(byte[], NPTypeCode, long, long)
Interpret a buffer as a 1-dimensional array.
public static NDArray frombuffer(byte[] buffer, NPTypeCode dtype, long count = -1, long offset = 0)
Parameters
bufferbyte[]An object that exposes the buffer interface.
dtypeNPTypeCodeData-type of the returned array. Default is float64.
countlongNumber of items to read. -1 means all data in the buffer.
offsetlongStart reading the buffer from this offset (in bytes). Default is 0.
Returns
- NDArray
1-dimensional NDArray with data interpreted from the buffer.
frombuffer(byte[], string, long, long)
Interpret a buffer as a 1-dimensional array.
public static NDArray frombuffer(byte[] buffer, string dtype, long count = -1, long offset = 0)
Parameters
bufferbyte[]An object that exposes the buffer interface.
dtypestringData-type string (e.g., ">u4" for big-endian uint32).
countlongNumber of items to read. -1 means all data in the buffer.
offsetlongStart reading the buffer from this offset (in bytes). Default is 0.
Returns
- NDArray
1-dimensional NDArray with data interpreted from the buffer.
Remarks
Note: Big-endian dtype strings (">u4", ">i4", etc.) require a COPY to perform byte swapping. Little-endian and native endian create views without copying.
frombuffer(nint, long, DType, long, long, Action)
Interpret unmanaged memory at a pointer as a 1-dimensional array.
public static NDArray frombuffer(nint address, long byteLength, DType dtype = null, long count = -1, long offset = 0, Action dispose = null)
Parameters
addressnintPointer to the start of the buffer.
byteLengthlongTotal length of the buffer in bytes.
dtypeDTypeData-type of the returned array. Default is float64.
countlongNumber of items to read. -1 means all data.
offsetlongByte offset into the buffer. Default is 0.
disposeActionOptional cleanup action called when NDArray is disposed. Use to transfer ownership: dispose: () => Marshal.FreeHGlobal(ptr) If null, caller is responsible for memory lifetime (view semantics).
Returns
- NDArray
1-dimensional NDArray viewing/owning the memory.
Examples
// View only (caller manages lifetime): var arr = np.frombuffer(ptr, length, typeof(float));
// Take ownership (NumSharp frees on dispose): var ptr = Marshal.AllocHGlobal(1024); var arr = np.frombuffer(ptr, 1024, typeof(float), dispose: () => Marshal.FreeHGlobal(ptr));
frombuffer(nint, long, NPTypeCode, long, long, Action)
Interpret unmanaged memory at a pointer as a 1-dimensional array.
public static NDArray frombuffer(nint address, long byteLength, NPTypeCode dtype, long count = -1, long offset = 0, Action dispose = null)
Parameters
Returns
frombuffer(Memory<byte>, DType, long, long)
Interpret a Memory<byte> as a 1-dimensional array. Creates a view if backed by an array, otherwise copies.
public static NDArray frombuffer(Memory<byte> memory, DType dtype = null, long count = -1, long offset = 0)
Parameters
memoryMemory<byte>The memory to interpret.
dtypeDTypeData-type of the returned array. Default is float64.
countlongNumber of items to read. -1 means all data.
offsetlongByte offset within the memory. Default is 0.
Returns
- NDArray
1-dimensional NDArray.
frombuffer(Memory<byte>, NPTypeCode, long, long)
Interpret a Memory<byte> as a 1-dimensional array.
public static NDArray frombuffer(Memory<byte> memory, NPTypeCode dtype, long count = -1, long offset = 0)
Parameters
memoryMemory<byte>dtypeNPTypeCodecountlongoffsetlong
Returns
frombuffer(ReadOnlySpan<byte>, DType, long, long)
Interpret a ReadOnlySpan as a 1-dimensional array. Note: ReadOnlySpan cannot be pinned, so this always creates a copy.
public static NDArray frombuffer(ReadOnlySpan<byte> buffer, DType dtype = null, long count = -1, long offset = 0)
Parameters
bufferReadOnlySpan<byte>dtypeDTypecountlongoffsetlong
Returns
frombuffer(ReadOnlySpan<byte>, NPTypeCode, long, long)
Interpret a ReadOnlySpan as a 1-dimensional array. Note: ReadOnlySpan cannot be pinned, so this always creates a copy.
public static NDArray frombuffer(ReadOnlySpan<byte> buffer, NPTypeCode dtype, long count = -1, long offset = 0)
Parameters
bufferReadOnlySpan<byte>dtypeNPTypeCodecountlongoffsetlong
Returns
frombuffer(void*, long, DType, long, long, Action)
Interpret unmanaged memory at a pointer as a 1-dimensional array.
public static NDArray frombuffer(void* address, long byteLength, DType dtype = null, long count = -1, long offset = 0, Action dispose = null)
Parameters
addressvoid*Pointer to the start of the buffer.
byteLengthlongTotal length of the buffer in bytes.
dtypeDTypeData-type of the returned array. Default is float64.
countlongNumber of items to read. -1 means all data.
offsetlongByte offset into the buffer. Default is 0.
disposeActionOptional cleanup action called when NDArray is disposed.
Returns
- NDArray
1-dimensional NDArray viewing/owning the memory.
frombuffer(void*, long, NPTypeCode, long, long, Action)
Interpret unmanaged memory at a pointer as a 1-dimensional array.
public static NDArray frombuffer(void* address, long byteLength, NPTypeCode dtype, long count = -1, long offset = 0, Action dispose = null)
Parameters
Returns
frombuffer<TSource>(TSource[], DType, long, long)
Reinterpret a typed array as a different dtype. Like NumPy's view() but via frombuffer semantics.
public static NDArray frombuffer<TSource>(TSource[] array, DType dtype = null, long count = -1, long offset = 0) where TSource : unmanaged
Parameters
arrayTSource[]The source array to reinterpret.
dtypeDTypeTarget data-type. Default preserves source type.
countlongNumber of items of target dtype. -1 for all.
offsetlongByte offset. Default is 0.
Returns
- NDArray
1-dimensional NDArray viewing the array as the target dtype.
Type Parameters
TSourceSource element type.
Examples
var ints = new int[] { 1, 2, 3, 4 }; var asBytes = np.frombuffer(ints, typeof(byte)); // 16 bytes var asFloats = np.frombuffer(ints, typeof(float)); // 4 floats (same bits)
frombuffer<TSource>(TSource[], NPTypeCode, long, long)
Reinterpret a typed array as a different dtype.
public static NDArray frombuffer<TSource>(TSource[] array, NPTypeCode dtype, long count = -1, long offset = 0) where TSource : unmanaged
Parameters
arrayTSource[]dtypeNPTypeCodecountlongoffsetlong
Returns
Type Parameters
TSource
fromfile(Stream, DType, int, string, long)
Construct an array from data in an open Stream (the file-object form). Reads from the stream's current position and leaves it open.
public static NDArray fromfile(Stream stream, DType dtype = null, int count = -1, string sep = "", long offset = 0)
Parameters
streamStreamdtypeDTypeElement type. For binary files it sets the item size; defaults to double.
countintNumber of items to read.
-1(default) reads the whole file.sepstringSeparator between items for a text file. Empty (default) reads binary. A separator containing spaces matches runs of whitespace; a whitespace-only separator splits on any whitespace run.
offsetlongBytes to skip from the file's current position. Binary files only.
Returns
Remarks
fromfile(string, DType, int, string, long)
Construct an array from data in a text or binary file. Efficient for binary data of a known dtype, and parses simply-formatted text files. Data written with tofile(string, string, string) can be read back with this function.
public static NDArray fromfile(string file, DType dtype = null, int count = -1, string sep = "", long offset = 0)
Parameters
filestringA filename.
dtypeDTypeElement type. For binary files it sets the item size; defaults to double.
countintNumber of items to read.
-1(default) reads the whole file.sepstringSeparator between items for a text file. Empty (default) reads binary. A separator containing spaces matches runs of whitespace; a whitespace-only separator splits on any whitespace run.
offsetlongBytes to skip from the file's current position. Binary files only.
Returns
Remarks
fromstring(string, DType, int, string)
Construct a 1-D array from the numbers in a text string.
public static NDArray fromstring(string @string, DType dtype = null, int count = -1, string sep = null)
Parameters
stringstringThe text to parse. Numbers are separated by
sep.dtypeDTypeElement type of the result (default double).
countintNumber of items to read;
-1(default) reads all of them.sepstringSeparator between numbers. A separator containing spaces matches runs of whitespace (a whitespace-only separator splits on any whitespace run). An empty or
nullseparator selects the removed binary mode and raises ValueError — use frombuffer(byte[],Type,long,long) instead.
Returns
Remarks
Parity with NumPy 2.4.2's np.fromstring (text mode). Shares fromfile(string, DType, int, string, long)'s
text reader, so item parsing, the single-trailing-separator rule and the verbatim
"unmatched data" error all match it.
https://numpy.org/doc/stable/reference/generated/numpy.fromstring.html
full(Shape, object, DType, string)
Return a new array of given shape and type, filled with fill_value.
public static NDArray full(Shape shape, object fill_value, DType dtype = null, string device = null)
Parameters
shapeShapeShape of the array, e.g., (2, 3) or 2.
fill_valueobjectFill value (scalar).
dtypeDTypeThe desired dtype for the array — one descriptor parameter, like NumPy's
dtype: a C# Type, an NPTypeCode, a NumPy dtype string ("f4") or a DType all convert implicitly. Default (null) infers from fill_value.devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity).
Returns
- NDArray
Array of fill_value with the given shape, dtype, and order.
Remarks
full(int[], object)
Return a new array of given shape and type, filled with fill_value.
public static NDArray full(int[] shape, object fill_value)
Parameters
Returns
- NDArray
Array of fill_value with the given shape, dtype, and order.
Remarks
full(long[], object)
Return a new array of given shape and type, filled with fill_value.
public static NDArray full(long[] shape, object fill_value)
Parameters
Returns
- NDArray
Array of fill_value with the given shape, dtype, and order.
Remarks
full_like(NDArray, object, DType, char, string)
Return a full array with the same shape and type as a given array.
public static NDArray full_like(NDArray a, object fill_value, DType dtype, char order, string device = null)
Parameters
aNDArrayThe shape and data-type of a define these same attributes of the returned array.
fill_valueobjectFill value.
dtypeDTypeOverrides the data type of the result.
ordercharMemory layout: 'C', 'F', 'A' or 'K' (default, preserves source layout).
devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity).
Returns
- NDArray
Array of fill_value with the same shape and type as a.
Remarks
full_like(NDArray, object, DType, string)
Return a full array with the same shape and type as a given array.
public static NDArray full_like(NDArray a, object fill_value, DType dtype = null, string device = null)
Parameters
aNDArrayThe shape and data-type of a define these same attributes of the returned array.
fill_valueobjectFill value.
dtypeDTypeOverrides the data type of the result.
devicestring
Returns
- NDArray
Array of fill_value with the same shape and type as a.
Remarks
full<T>(int[], object)
Return a new array of given shape and type, filled with fill_value.
public static NDArray full<T>(int[] shape, object fill_value) where T : unmanaged
Parameters
Returns
- NDArray
Array of fill_value with the given shape, dtype, and order.
Type Parameters
T
Remarks
full<T>(long[], object)
Return a new array of given shape and type, filled with fill_value.
public static NDArray full<T>(long[] shape, object fill_value) where T : unmanaged
Parameters
Returns
- NDArray
Array of fill_value with the given shape, dtype, and order.
Type Parameters
T
Remarks
get_printoptions()
Return the current print options as a dictionary (NumPy's np.get_printoptions).
public static IReadOnlyDictionary<string, object> get_printoptions()
Returns
Remarks
getbufsize()
Return the size of the buffer used in ufuncs (the default buffer size for buffered NDIter/ufunc iteration on the calling thread).
public static long getbufsize()
Returns
- long
Size of the ufunc buffer, in elements. Defaults to 8192 (NumPy's
NPY_BUFSIZE).
Remarks
Mirrors numpy.getbufsize(). The value is thread-local: it reflects the last
setbufsize(long) call on the current thread (or the 8192 default if none),
matching NumPy 2.x's context-local error/buffer state. The buffer size affects only how
buffered iteration is chunked internally — it never changes any computed result.
np.getbufsize(); // 8192
np.setbufsize(4096); // returns 8192 (the previous size)
np.getbufsize(); // 4096
greater(NDArray, NDArray, NDArray, NDArray, DType)
Return (x1 > x2) element-wise.
Mirrors NumPy's ufunc signature: greater(x1, x2, /, out=None, *, where=True, dtype=None).
A plain call returns a bool-dtype array (the instance is an NDArray<TDType> of bool —
cast or use the > operator for the typed wrapper).
public static NDArray greater(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayInput array.
x2NDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): comparisons have bool loops only — any non-bool request raises the no-loop TypeError.
Returns
Remarks
greater(NDArray, object)
Return (x1 > x2) element-wise with scalar.
public static NDArray<bool> greater(NDArray x1, object x2)
Parameters
Returns
greater(object, NDArray)
Return (x1 > x2) element-wise with scalar on left.
public static NDArray<bool> greater(object x1, NDArray x2)
Parameters
Returns
greater_equal(NDArray, NDArray, NDArray, NDArray, DType)
Return (x1 >= x2) element-wise.
Mirrors NumPy's ufunc signature: greater_equal(x1, x2, /, out=None, *, where=True, dtype=None).
A plain call returns a bool-dtype array (the instance is an NDArray<TDType> of bool —
cast or use the >= operator for the typed wrapper).
public static NDArray greater_equal(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayInput array.
x2NDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): comparisons have bool loops only — any non-bool request raises the no-loop TypeError.
Returns
Remarks
greater_equal(NDArray, object)
Return (x1 >= x2) element-wise with scalar.
public static NDArray<bool> greater_equal(NDArray x1, object x2)
Parameters
Returns
greater_equal(object, NDArray)
Return (x1 >= x2) element-wise with scalar on left.
public static NDArray<bool> greater_equal(object x1, NDArray x2)
Parameters
Returns
hsplit(NDArray, int)
Split an array into multiple sub-arrays horizontally (column-wise).
public static NDArray[] hsplit(NDArray ary, int indices_or_sections)
Parameters
aryNDArrayArray to be divided into sub-arrays.
indices_or_sectionsintIf an integer, N, the array will be divided into N equal arrays along the axis. If such a split is not possible, an error is raised.
Returns
- NDArray[]
A list of sub-arrays as views into ary.
Remarks
For 1-D arrays, splits along axis 0. For 2-D+ arrays, splits along axis 1 (columns). https://numpy.org/doc/stable/reference/generated/numpy.hsplit.html
hsplit(NDArray, int[])
Split an array into multiple sub-arrays horizontally (column-wise).
public static NDArray[] hsplit(NDArray ary, int[] indices)
Parameters
aryNDArrayArray to be divided into sub-arrays.
indicesint[]A 1-D array of sorted integers indicating where along the axis the array is split. For example, [2, 3] would result in ary[:2], ary[2:3], ary[3:].
Returns
- NDArray[]
A list of sub-arrays as views into ary.
Remarks
For 1-D arrays, splits along axis 0. For 2-D+ arrays, splits along axis 1 (columns). https://numpy.org/doc/stable/reference/generated/numpy.hsplit.html
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 static NDArray hstack(params NDArray[] tup)
Parameters
tupNDArray[]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
identity(int, DType)
Return the identity array. The identity array is a square array with ones on the main diagonal.
public static NDArray identity(int n, DType dtype = null)
Parameters
nintNumber of rows (and columns) in n x n output.
dtypeDTypeData-type of the output. Defaults to double.
Returns
- NDArray
n x n array with its main diagonal set to one, and all other elements 0.
Remarks
iinfo(DType)
Machine limits for integer types.
public static iinfo iinfo(DType dtype)
Parameters
dtypeDTypeThe integer dtype — one descriptor parameter, like NumPy's: a C# Type (
typeof(int)), an NPTypeCode, a NumPy dtype string or a DType (np.int32,arr.dtype) all convert implicitly.
Returns
- iinfo
An iinfo object describing the integer type limits.
Examples
var info = np.iinfo(np.int32);
Console.WriteLine(info.bits); // 32
Console.WriteLine(info.min); // -2147483648
Console.WriteLine(info.max); // 2147483647
Remarks
iinfo(NDArray)
Machine limits for integer types.
public static iinfo iinfo(NDArray arr)
Parameters
arrNDArrayAn NDArray with integer dtype.
Returns
- iinfo
An iinfo object describing the array's integer type limits.
Examples
var a = np.array(new int[] {1, 2, 3});
var info = np.iinfo(a);
Console.WriteLine(info.bits); // 32
Exceptions
- ArgumentNullException
Thrown if arr is null.
iinfo(string)
Machine limits for integer types.
public static iinfo iinfo(string dtypeName)
Parameters
dtypeNamestringA dtype string (e.g., "int32", "uint8", "bool").
Returns
- iinfo
An iinfo object describing the integer type limits.
Examples
var info = np.iinfo("int32");
Console.WriteLine(info.bits); // 32
Exceptions
- ArgumentException
Thrown if dtypeName is not a valid integer dtype.
iinfo<T>()
Machine limits for integer types.
public static iinfo iinfo<T>() where T : struct
Returns
- iinfo
An iinfo object describing the integer type limits.
Type Parameters
TAn integer type (bool, byte, short, ushort, int, uint, long, ulong, char).
Examples
var info = np.iinfo<int>();
Console.WriteLine(info.bits); // 32
imag(NDArray)
Return the imaginary part of the complex argument, element-wise.
One of the four basic complex-number accessors (with real(NDArray), angle(NDArray, bool)
and conjugate(NDArray, NDArray, NDArray, DType)) — the standard post-FFT spectrum component extractors: for
A = np.fft.fft(a), A.imag / np.imag(A) is the imaginary component.
public static NDArray imag(NDArray val)
Parameters
valNDArrayInput array.
Returns
- NDArray
For a COMPLEX input: a float64 VIEW onto the imaginary lane — it SHARES memory with
valand is writeable, sonp.imag(z)[i] = xwrites through toz[i]'s imaginary part (reproducing NumPy'sz.imag; complex128 -> float64). For a REAL / integer / boolean input: a fresh, READ-ONLY all-zeros array of the same shape and dtype (the imaginary part of a real number is zero), matching NumPy exactly.
Remarks
indices(int[], DType)
Return an array representing the indices of a grid. Dense form — for the sparse form, see indices_sparse(int[], DType).
public static NDArray indices(int[] dimensions, DType dtype = null)
Parameters
Returns
- NDArray
Single dense array of shape
(len(dimensions), *dimensions). The d-th sub-array contains the d-th coordinate of each output position.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.indices.html
NumPy's sparse=True mode is exposed as the separate method
indices_sparse(int[], DType) — C# can't change return type based on a
parameter the way Python's dynamic typing does, so splitting the API is
clearer than throwing from a shared signature.
indices_sparse(int[], DType)
Sparse counterpart to indices(int[], DType) — returns a tuple of
broadcast-shaped arrays where each axis-d array has shape
(1, …, 1, dimensions[d], 1, …, 1). Equivalent to NumPy's
np.indices(dimensions, sparse=True).
public static NDArray[] indices_sparse(int[] dimensions, DType dtype = null)
Parameters
Returns
- NDArray[]
inner(NDArray, NDArray)
Inner product of two arrays — a sum product over the LAST axis of each.
public static NDArray inner(NDArray a, NDArray b)
Parameters
Returns
- NDArray
Shape
a.shape[:-1] + b.shape[:-1]. A 0-d operand makes this an ordinary multiply, and two 1-D operands give a 0-d scalar.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.inner.html
Unlike dot(NDArray, NDArray, NDArray), which contracts a's last axis against b's
SECOND-TO-last, inner contracts the last axis of both. NumPy implements that by
swapping b's last two axes and handing the pair to the very same dispatcher
np.dot uses (PyArray_MatrixProduct2) — which is why an unaligned
inner reports b's shape ALREADY TRANSPOSED:
np.inner(ones((2,3)), ones((3,2))) raises
"shapes (2,3) and (2,3) not aligned: 3 (dim 1) != 2 (dim 0)".
Complex operands are NOT conjugated (use vdot(NDArray, NDArray) or vecdot(NDArray, NDArray, NDArray, int[][], int?, bool, DType) for the conjugating form).
insert(NDArray, NDArray, NDArray, int?)
NDArray-typed obj. Dispatches:
- 0-D / 1-element integer ⇒ scalar single-index path.
- 1-D bool ⇒ flatnonzero(NDArray) ⇒ multi-index path.
- 1-D integer ⇒ multi-index path.
- > 1-D ⇒ ArgumentException matching NumPy's "index array argument obj to insert must be one dimensional or scalar".
public static NDArray insert(NDArray arr, NDArray obj, NDArray values, int? axis = null)
Parameters
Returns
insert(NDArray, NDArray, object, int?)
NDArray-obj overload accepting a scalar value.
public static NDArray insert(NDArray arr, NDArray obj, object value, int? axis = null)
Parameters
Returns
insert(NDArray, Slice, NDArray, int?)
Slice-obj overload. obj is expanded via
Python slice.indices(N) into an indices array, then the
multi-index branch runs.
public static NDArray insert(NDArray arr, Slice obj, NDArray values, int? axis = null)
Parameters
Returns
insert(NDArray, Slice, object, int?)
Slice-obj overload accepting a scalar value.
public static NDArray insert(NDArray arr, Slice obj, object value, int? axis = null)
Parameters
Returns
insert(NDArray, int, NDArray, int?)
Insert values along axis
before the position obj. Scalar-obj path.
public static NDArray insert(NDArray arr, int obj, NDArray values, int? axis = null)
Parameters
Returns
Remarks
insert(NDArray, int, object, int?)
int-overload accepting a scalar value.
public static NDArray insert(NDArray arr, int obj, object value, int? axis = null)
Parameters
Returns
insert(NDArray, int[], NDArray, int?)
int[]-obj overload. Always routes through the multi-index branch
(NumPy parity: np.insert(arr, [1], v) != np.insert(arr, 1, v)
when v has multiple axes, even though both have one insertion point).
public static NDArray insert(NDArray arr, int[] obj, NDArray values, int? axis = null)
Parameters
Returns
insert(NDArray, int[], object, int?)
int[]-obj overload accepting a scalar value.
public static NDArray insert(NDArray arr, int[] obj, object value, int? axis = null)
Parameters
Returns
insert(NDArray, long, NDArray, int?)
Long-index overload of insert(NDArray, int, NDArray, int?).
public static NDArray insert(NDArray arr, long obj, NDArray values, int? axis = null)
Parameters
Returns
insert(NDArray, long, object, int?)
Scalar-obj overload accepting a scalar value (NumPy: np.insert(a, 1, 99)).
Broadcasts the value to the required shape using arr.dtype.
public static NDArray insert(NDArray arr, long obj, object value, int? axis = null)
Parameters
Returns
insert(NDArray, long[], NDArray, int?)
long[]-obj overload.
public static NDArray insert(NDArray arr, long[] obj, NDArray values, int? axis = null)
Parameters
Returns
insert(NDArray, long[], object, int?)
long[]-obj overload accepting a scalar value.
public static NDArray insert(NDArray arr, long[] obj, object value, int? axis = null)
Parameters
Returns
interp(NDArray, NDArray, NDArray, double?, double?, double?)
One-dimensional linear interpolation for monotonically increasing sample points.
Returns the piecewise-linear interpolant to the discrete data points (xp, fp), evaluated
at each coordinate in x. Port of NumPy's numpy.interp
(compiled_base.c::arr_interp + the _function_base_impl.py wrapper).
public static NDArray interp(NDArray x, NDArray xp, NDArray fp, double? left = null, double? right = null, double? period = null)
Parameters
xNDArrayThe x-coordinates at which to evaluate the interpolated values (any shape; the result has the same shape).
xpNDArrayThe x-coordinates of the data points — 1-D, must be increasing unless
periodis given.fpNDArrayThe y-coordinates of the data points, same length as xp (float or complex).
leftdouble?Value returned for
x < xp[0]; default isfp[0]. Ignored whenperiodis given.rightdouble?Value returned for
x > xp[-1]; default isfp[-1]. Ignored whenperiodis given.perioddouble?A period for the x-coordinates, allowing proper interpolation of angular x-coordinates. Must be non-zero.
Returns
- NDArray
The interpolated values, same shape as x (float64, or complex128 when fp is complex). A scalar (0-d) if x is a scalar.
Remarks
interp(NDArray, NDArray, NDArray, Complex?, Complex?, double?)
Complex-fp overload of interp(NDArray, NDArray, NDArray, double?, double?, double?)
accepting complex left / right fill values.
public static NDArray interp(NDArray x, NDArray xp, NDArray fp, Complex? left, Complex? right = null, double? period = null)
Parameters
Returns
Remarks
intersect1d(NDArray, NDArray)
Find the intersection of two arrays (the bare-return form of np.intersect1d).
Return the sorted, unique values that are in both of the input arrays.
public static NDArray intersect1d(NDArray ar1, NDArray ar2)
Parameters
ar1NDArrayInput array (flattened if not already 1-D).
ar2NDArrayInput array (flattened if not already 1-D).
Returns
- NDArray
Sorted 1-D array of common, unique elements.
Remarks
intersect1d(NDArray, NDArray, bool)
Find the intersection of two arrays (bare-return, with the assume_unique speed hint).
Return the sorted, unique values that are in both of the input arrays.
public static NDArray intersect1d(NDArray ar1, NDArray ar2, bool assume_unique)
Parameters
ar1NDArrayInput array (flattened if not already 1-D).
ar2NDArrayInput array (flattened if not already 1-D).
assume_uniqueboolIf True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.
Returns
- NDArray
Sorted 1-D array of common, unique elements.
Remarks
intersect1d(NDArray, NDArray, bool, bool)
Find the intersection of two arrays, returning the indices of the common values.
Mirrors NumPy's tuple return: np.intersect1d(a, b, return_indices=True) — both
assume_unique and return_indices are optional so the
keyword-only return_indices call binds here (the bare overloads above have no
return_indices parameter, so they cannot capture it — no ambiguity with this one).
public static NDArray[] intersect1d(NDArray ar1, NDArray ar2, bool assume_unique = false, bool return_indices = false)
Parameters
ar1NDArrayInput array (flattened if not already 1-D).
ar2NDArrayInput array (flattened if not already 1-D).
assume_uniqueboolIf True, the input arrays are both assumed to be unique.
return_indicesboolIf True, also return the indices of the first occurrences of the common values in
ar1andar2.
Returns
- NDArray[]
[values]whenreturn_indicesis False, otherwise[values, comm1, comm2].
Remarks
invert(NDArray, NDArray, NDArray, DType)
Compute bit-wise inversion, or bit-wise NOT, element-wise. Computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays.For signed integer inputs, the two's complement is returned. In a two's-complement system negative numbers are represented by the two's complement of the absolute value.
public static NDArray invert(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
- NDArray
Result. This is a scalar if x is a scalar.
Remarks
isclose(NDArray, NDArray, double, double, bool)
Returns a boolean array where two arrays are element-wise equal within a
tolerance.
The tolerance values are positive, typically very small numbers.The
relative difference (rtol * abs(b)) and the absolute difference
atol are added together to compare against the absolute difference
between a and b.
Warning: The default atol is not appropriate for comparing numbers
that are much smaller than one(see Notes).
See also allclose(NDArray, NDArray, double, double, bool)
Notes: For finite values, isclose uses the following equation to test whether two floating point values are equivalent.
absolute(`a` - `b`) less than or equal to (`atol` + `rtol` * absolute(`b`))
Unlike the built-in math.isclose, the above equation is not symmetric
in a and b -- it assumes b is the reference value -- so that
isclose(a, b) might be different from isclose(b, a). Furthermore,
the default value of atol is not zero, and is used to determine what
small values should be considered close to zero.The default value is
appropriate for expected values of order unity: if the expected values
are significantly smaller than one, it can result in false positives.
atol should be carefully selected for the use case at hand. A zero value
for atol will result in False if either a or b is zero.
public static NDArray<bool> isclose(NDArray a, NDArray b, double rtol = 1E-05, double atol = 1E-08, bool equal_nan = false)
Parameters
aNDArrayInput array to compare with b
bNDArrayInput array to compare with a.
rtoldoubleThe relative tolerance parameter(see Notes)
atoldoubleThe absolute tolerance parameter(see Notes)
equal_nanboolWhether to compare NaN's as equal. If True, NaN's in
awill be considered equal to NaN's inbin the output array.
Returns
- NDArray<bool>
Returns a boolean array of where
aandbare equal within the given tolerance.If bothaandbare scalars, returns a single boolean value.
iscomplex(NDArray)
Returns a bool array, where True if input element is complex.
public static NDArray iscomplex(NDArray a)
Parameters
aNDArrayInput array.
Returns
- NDArray
Boolean array of same shape, True where element has non-zero imaginary part.
Examples
var a = np.array(new int[] {1, 2, 3});
np.iscomplex(a) // [False, False, False]
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.iscomplex.html
For non-complex arrays, all elements are considered not complex. For complex arrays, elements with non-zero imaginary part are complex.
iscomplexobj(NDArray)
Return True if x is a complex type or an array of complex numbers.
public static bool iscomplexobj(NDArray a)
Parameters
aNDArrayInput array or scalar.
Returns
- bool
True if the array's dtype is complex.
Examples
var a = np.array(new int[] {1, 2, 3});
np.iscomplexobj(a) // False (dtype is int, not complex)
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.iscomplexobj.html
The type of the input is checked, not the value.
isdtype(DType, DType)
Returns True if the two descriptors are instances of the same DType class — NumPy's np.isdtype(dtype, other_dtype)
compares the scalar TYPES, so isdtype('M8[s]', 'M8[ns]') is True while isdtype(float32, float64) is False.
public static bool isdtype(DType dtype, DType kind)
Parameters
Returns
isdtype(DType, string)
Returns True if the descriptor is of a specified category — NumPy 2.x's np.isdtype(dtype, kind) over a
DType: kind is one of "bool", "signed integer",
"unsigned integer", "integral", "real floating", "complex floating", "numeric"
(case-sensitive, as in NumPy). The datetime classes belong to none of them (NumPy builds the categories from
sctypes, which exclude datetime64/timedelta64).
This is the ONE entry for every dtype spelling: a C# Type (typeof(int)), an
NPTypeCode (NPTypeCode.Int32) or a dtype string all convert implicitly to DType
(the earlier NPTypeCode/Type twins accepted issubdtype's looser vocabulary — "floating",
"integer" — which NumPy's isdtype rejects; they were folded into this overload).
public static bool isdtype(DType dtype, string kind)
Parameters
Returns
Examples
np.isdtype(NPTypeCode.Int32, "integral") // True
np.isdtype(typeof(double), "real floating") // True
np.isdtype(np.int32, "numeric") // True
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.isdtype.html — a NumPy 2.0+ function.
Exceptions
- ValueError
kind argument is a string, but '…' is not a known kind name.— verbatim NumPy.
isdtype(DType, params string[])
Returns True if the descriptor is of any of the specified categories (NumPy's tuple form).
public static bool isdtype(DType dtype, params string[] kinds)
Parameters
Returns
isdtype(NDArray, string)
Returns True if the array's dtype is of a specified category (NumSharp convenience: NumPy's isdtype takes
only a dtype, so this is np.isdtype(arr.dtype, kind)).
public static bool isdtype(NDArray arr, string kind)
Parameters
Returns
- bool
True if array's dtype belongs to the specified category.
Exceptions
- ArgumentNullException
Thrown if arr is null.
isdtype(NDArray, string[])
Returns True if the array's dtype is of any of the specified categories.
public static bool isdtype(NDArray arr, string[] kinds)
Parameters
Returns
- bool
True if array's dtype belongs to any of the specified categories.
Exceptions
- ArgumentNullException
Thrown if arr is null.
isdtype(string, string)
isdtype(DType, string) for a dtype STRING (np.isdtype("i4", "integral")). Exists so that a
string first argument binds the dtype grammar rather than NumSharp's string→NDArray conversion.
public static bool isdtype(string dtype, string kind)
Parameters
Returns
isdtype(string, params string[])
isdtype(DType, params string[]) for a dtype STRING.
public static bool isdtype(string dtype, params string[] kinds)
Parameters
Returns
isfinite(NDArray, NDArray, NDArray, DType)
Test element-wise for finiteness (not infinity and not Not a Number).
Mirrors NumPy's ufunc signature: isfinite(x, /, out=None, *, where=True, dtype=None).
A plain call returns a bool-dtype array (the instance is an NDArray<TDType> of bool).
public static NDArray isfinite(NDArray a, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
aNDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): the predicate has bool loops only — any non-bool request raises the no-loop TypeError.
Returns
Remarks
isfortran(NDArray)
Check if the array is Fortran contiguous but not C contiguous — exactly NumPy's
a.flags.fnc (numpy/_core/numeric.py::isfortran, a pure flags read).
public static bool isfortran(NDArray a)
Parameters
aNDArrayInput array.
Returns
- bool
True iff
ais F-contiguous and not C-contiguous. Note the asymmetry NumPy documents: a 1-D (or 0-d / empty) array is BOTH C- and F-contiguous, soisfortranis False for it — this reports column-major MEMORY ORDER, not mere F-contiguity (usea.flags.f_contiguousfor that).
Remarks
isin(NDArray, NDArray, bool, bool, string)
Calculates element in test_elements, broadcasting over element only.
Returns a boolean array of the same shape as element that is True where an
element of element is in test_elements and False otherwise.
public static NDArray isin(NDArray element, NDArray test_elements, bool assume_unique = false, bool invert = false, string kind = null)
Parameters
elementNDArrayInput array.
test_elementsNDArrayThe values against which to test each value of
element. Flattened before use.assume_uniqueboolIf True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.
invertboolIf True, the values in the returned array are inverted, as if calculating
element not in test_elements. Default is False.kindstringThe algorithm to use:
null(auto),"sort", or"table". Does not affect the result, only speed/memory."table"is only valid for boolean/integer arrays.
Returns
- NDArray
A boolean array with the same shape as
element.
Remarks
isinf(NDArray, NDArray, NDArray, DType)
Test element-wise for positive or negative infinity.
Mirrors NumPy's ufunc signature: isinf(x, /, out=None, *, where=True, dtype=None).
A plain call returns a bool-dtype array (the instance is an NDArray<TDType> of bool).
public static NDArray isinf(NDArray a, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
aNDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): the predicate has bool loops only — any non-bool request raises the no-loop TypeError.
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.isinf.html
- Float/Double: True if value is +Inf or -Inf
- Integer types: Always False (integers cannot be Inf)
- NaN: Returns False (NaN is not infinity)
isnan(NDArray, NDArray, NDArray, DType)
Test element-wise for Not a Number.
Mirrors NumPy's ufunc signature: isnan(x, /, out=None, *, where=True, dtype=None).
A plain call returns a bool-dtype array (the instance is an NDArray<TDType> of bool).
public static NDArray isnan(NDArray a, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
aNDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): the predicate has bool loops only — any non-bool request raises the no-loop TypeError.
Returns
Remarks
isneginf(NDArray, NDArray)
Test element-wise for negative infinity, return result as a bool array.
public static NDArray isneginf(NDArray x, NDArray @out = null)
Parameters
xNDArrayThe input array.
outNDArrayA location into which the result is stored (NumPy's positional
out). If provided it must have a shape the input broadcasts to; if its dtype is numeric the result is stored as 0/1, if boolean as False/True. The same instance is returned. Ifnull, a freshly allocated boolean array is returned.
Returns
- NDArray
A boolean array (or
out), True where the element is -Inf.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.isneginf.html
Port of NumPy's numpy.isneginf (numpy/lib/_ufunclike_impl.py), defined as
logical_and(isinf(x), signbit(x)) — i.e. exactly x == -inf. Integer and boolean
inputs return all-False. A complex input raises TypeError
("This operation is not supported for complex128 values because it would be ambiguous."),
matching NumPy 2.4.2.
isposinf(NDArray, NDArray)
Test element-wise for positive infinity, return result as a bool array.
public static NDArray isposinf(NDArray x, NDArray @out = null)
Parameters
xNDArrayThe input array.
outNDArrayA location into which the result is stored (NumPy's positional
out). If provided it must have a shape the input broadcasts to; if its dtype is numeric the result is stored as 0/1, if boolean as False/True. The same instance is returned. Ifnull, a freshly allocated boolean array is returned.
Returns
- NDArray
A boolean array (or
out), True where the element is +Inf.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.isposinf.html
Port of NumPy's numpy.isposinf (numpy/lib/_ufunclike_impl.py), defined as
logical_and(isinf(x), ~signbit(x)) — i.e. exactly x == +inf. Integer and boolean
inputs return all-False (they cannot be infinite). A complex input raises
TypeError ("This operation is not supported for complex128 values because it would
be ambiguous.") — NumPy's signbit is ambiguous on complex, so the whole function is —
matching NumPy 2.4.2.
isreal(NDArray)
Returns a bool array, where True if input element is real.
public static NDArray isreal(NDArray a)
Parameters
aNDArrayInput array.
Returns
- NDArray
Boolean array of same shape, True where element has no imaginary part.
Examples
var a = np.array(new int[] {1, 2, 3});
np.isreal(a) // [True, True, True]
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.isreal.html
For non-complex arrays, all elements are considered real. For complex arrays, elements with zero imaginary part are real.
isrealobj(NDArray)
Return True if x is a not complex type or an array of complex numbers.
public static bool isrealobj(NDArray a)
Parameters
aNDArrayInput array or scalar.
Returns
- bool
True if the array's dtype is not complex.
Examples
var a = np.array(new int[] {1, 2, 3});
np.isrealobj(a) // True (dtype is int, not complex)
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.isrealobj.html
The type of the input is checked, not the value. Even an array of complex numbers with zero imaginary parts will return False.
isscalar(object)
Returns true incase of a number, bool or string. If null, returns false.
public static bool isscalar(object obj)
Parameters
objobject
Returns
Remarks
issctype(object)
Determines whether the given object represents a scalar dtype.
public static bool issctype(object rep)
Parameters
repobjectThe object to check.
Returns
- bool
True if rep represents a scalar dtype.
Examples
np.issctype(typeof(int)) // True
np.issctype(NPTypeCode.Int32) // True
np.issctype(typeof(NDArray)) // False
Remarks
issubdtype(DType, DType)
Returns True if the scalar type of arg1 is the scalar type of arg2 or a
subclass of it — NumPy's issubdtype(dtype1, dtype2) over two DESCRIPTORS, which compares their
.type: instances of one class compare equal whatever their parameters
(issubdtype('M8[s]', 'M8[ns]') is True, as is issubdtype('>i4', 'i4')), and distinct concrete
classes are never related (issubdtype(int32, int64) is False).
public static bool issubdtype(DType arg1, DType arg2)
Parameters
Returns
issubdtype(DType, string)
Returns True if the descriptor's scalar type is under the abstract category arg2
("generic", "number", "integer", "signedinteger", "unsignedinteger",
"inexact", "floating", "complexfloating", "bool") — NumPy's scalar hierarchy, in
which datetime64 sits directly under generic ("Datetime doesn't fit in any category") and
timedelta64 under signedinteger ("Timedelta is an integer with an associated unit").
public static bool issubdtype(DType arg1, string arg2)
Parameters
Returns
issubdtype(NDArray, string)
Returns True if first argument is a typecode lower/equal in type hierarchy.
public static bool issubdtype(NDArray arr, string arg2)
Parameters
arrNDArrayNDArray - array whose dtype to check.
arg2stringstring - string representing a typecode category.
Returns
- bool
True if array's dtype is a subtype of arg2 category.
Exceptions
- ArgumentNullException
Thrown if arr is null.
issubdtype(NPTypeCode, NPTypeCode)
Returns True if first argument is a typecode lower/equal in type hierarchy.
public static bool issubdtype(NPTypeCode arg1, NPTypeCode arg2)
Parameters
arg1NPTypeCodedtype - dtype representing a typecode.
arg2NPTypeCodedtype - dtype representing a typecode.
Returns
- bool
True if arg1 is equal to or a subtype of arg2.
Remarks
When comparing two concrete types, returns true only if they are the same type. For hierarchy checks, use the (NPTypeCode, string) overload.
issubdtype(NPTypeCode, string)
Returns True if first argument is a typecode lower/equal in type hierarchy.
public static bool issubdtype(NPTypeCode arg1, string arg2)
Parameters
arg1NPTypeCodedtype or string - dtype or string representing a typecode.
arg2stringdtype or string - dtype or string representing a typecode.
Returns
- bool
True if arg1 is a subtype of arg2.
Examples
np.issubdtype(NPTypeCode.Int32, "integer") // True
np.issubdtype(NPTypeCode.Double, "floating") // True
np.issubdtype(NPTypeCode.Boolean, "integer") // False (NumPy 2.x)
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.issubdtype.html
Implementation mirrors NumPy's issubdtype which uses issubclass() on the type hierarchy defined in numpy/_core/src/multiarray/multiarraymodule.c.
Type hierarchy in NumPy:
- generic → number → integer/inexact
- integer → signedinteger/unsignedinteger
- inexact → floating/complexfloating
Note: In NumPy 2.x, bool is NOT a subtype of integer (it's directly under generic).
issubdtype(string, string)
Returns True if the dtype named by arg1 (a NumPy dtype string such as "i4" or
"M8[ns]") is under the abstract category arg2. Exists so that a string first argument
binds the dtype grammar rather than NumSharp's string→NDArray (character array) conversion.
public static bool issubdtype(string arg1, string arg2)
Parameters
Returns
issubdtype(Type, string)
Returns True if first argument is a typecode lower/equal in type hierarchy.
public static bool issubdtype(Type arg1, string arg2)
Parameters
arg1TypeType - CLR type representing a typecode.
arg2stringstring - string representing a typecode category.
Returns
- bool
True if arg1 is a subtype of arg2 category.
issubdtype(Type, Type)
Returns True if first argument is a typecode lower/equal in type hierarchy.
public static bool issubdtype(Type arg1, Type arg2)
Parameters
Returns
- bool
True if arg1 is equal to or a subtype of arg2.
issubsctype(NPTypeCode, NPTypeCode)
Determine if a class is a subclass of a second class.
public static bool issubsctype(NPTypeCode arg1, NPTypeCode arg2)
Parameters
arg1NPTypeCodeThe dtype to check.
arg2NPTypeCodeThe dtype to compare against.
Returns
- bool
True if arg1 is a subtype of arg2.
Remarks
iterable(object)
Check whether or not an object can be iterated over. Returns true if
y has an iterator method or is a sequence, and false otherwise.
public static bool iterable(object y)
Parameters
yobjectInput object.
Returns
- bool
trueif the object is iterable,falseotherwise.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.iterable.html
Port of NumPy's numpy.iterable (numpy/lib/_function_base_impl.py), whose whole
body is try: iter(y); return True; except TypeError: return False. It is a pure
predicate — it does NOT iterate the data, it only tests whether iteration is possible — so it
needs no kernel/NDIter/loop of any kind (O(1) rank/type check).
The one surprise NumPy documents is 0-dimensional arrays: although a 0-d NDArray
is a collection type, iter() on it raises TypeError("iteration over a 0-d array")
(see GetEnumerator()), so np.iterable(np.array(1.0)) is false
while any array of rank ≥ 1 (empty included) is true.
C# type mapping (each matches NumPy's iter() outcome, probed against NumPy 2.4.2):
null→ false (NumPy'siter(None)raises TypeError).- NDArray →
ndim != 0(0-d is the only non-iterable array). - string → true (Python strings are iterable).
- Any IEnumerable — C# arrays, lists, dictionaries, sets … → true.
- Everything else — the scalar value types int/double/bool/Complex/Half/decimal/char … → false.
Deliberate C# divergences (probed against NumPy 2.4.2): NumSharp maps Python's
iter()-ability onto C#'s IEnumerable — i.e. "is this foreach-able?".
Four inputs are iterable in Python but their C# analogs cannot be foreach'd, so they
return false here while NumPy returns true: a bare IEnumerator /
IEnumerator<T> cursor (a Python iterator is self-iterable, but a C# enumerator
has no GetEnumerator), and ValueTuple / Tuple / ITuple
(they implement no IEnumerable). Real ported code passes the collection itself —
an array, List, or NDArray, all foreach-able — which matches NumPy exactly.
ix_(params object[])
Construct an open mesh from multiple sequences.
public static NDArray[] ix_(params object[] args)
Parameters
argsobject[]N 1-D sequences of integer or boolean type. A boolean sequence is interpreted as a mask for the corresponding dimension (equivalent to passing nonzero(NDArray) of it). Accepts anything asanyarray(in object, DType, string) understands — NDArray, C# arrays, collections, tuples.
Returns
- NDArray[]
N arrays with N dimensions each, shape 1 in every axis but the k-th (which carries the k-th sequence). Together they form an open mesh:
a[np.ix_(rows, cols)]selects the cross producta[rows][:, cols].
Remarks
Port of NumPy 2.x numpy.ix_ (numpy/lib/_index_tricks_impl.py). The reshape is a
VIEW when the source permits one, so the outputs share memory with an NDArray
input (NumPy does the same — shares_memory is True there too) and remain writeable.
The dtype is PRESERVED, not forced to intp: ix_ performs no integer validation,
so a float or byte sequence comes back as float/byte and only fails later, at the indexing
call. The single exception is NumPy's: a non-ndarray input that turns out EMPTY is cast to
intp (int64) to avoid the float64 default of an untyped empty list.
https://numpy.org/doc/stable/reference/generated/numpy.ix_.html
Exceptions
- ValueError
A sequence is not 1-D ("Cross index must be 1 dimensional").
kron(NDArray, NDArray)
Kronecker product of two arrays.
Computes the Kronecker product, a composite array made of blocks of the second array
scaled by the first. If a.shape = (r0,r1,...,rN) and b.shape = (s0,s1,...,sN)
the result has shape (r0*s0, r1*s1, ..., rN*sN) with
kron(a,b)[k0,...,kN] = a[i0,...,iN] * b[j0,...,jN] where kt = it*st + jt.
The number of dimensions of a and b need not match —
the smaller is treated as if prepended with size-1 axes (NumPy's ndmin behaviour).
public static NDArray kron(NDArray a, NDArray b)
Parameters
Returns
- NDArray
A fresh, writeable, C-contiguous array. The result dtype follows NumPy's
multiplypromotion (NEP50). Ifbis 0-d the result is the element-wisea * b(which is itself the degenerate Kronecker product).
Remarks
left_shift(NDArray, NDArray)
Shift the bits of an integer to the left.
public static NDArray left_shift(NDArray x1, NDArray x2)
Parameters
x1NDArrayInput array (integer types only).
x2NDArrayNumber of bits to shift (integer types only).
Returns
- NDArray
Array with bits shifted left.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.left_shift.html
Bits are shifted to the left by appending x2 0s at the right of x1. Since the internal representation of numbers is in binary format, this operation is equivalent to multiplying x1 by 2**x2.
Example: np.left_shift(5, 2) = 20 # 0b101 -> 0b10100
left_shift(NDArray, object)
Shift the bits of an integer to the left by a scalar or array-like amount.
public static NDArray left_shift(NDArray x1, object x2)
Parameters
x1NDArrayInput array (integer types only).
x2objectNumber of bits to shift (scalar or array-like).
Returns
- NDArray
Array with bits shifted left.
less(NDArray, NDArray, NDArray, NDArray, DType)
Return (x1 < x2) element-wise.
Mirrors NumPy's ufunc signature: less(x1, x2, /, out=None, *, where=True, dtype=None).
A plain call returns a bool-dtype array (the instance is an NDArray<TDType> of bool —
cast or use the < operator for the typed wrapper).
public static NDArray less(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayInput array.
x2NDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): comparisons have bool loops only — any non-bool request raises the no-loop TypeError.
Returns
Remarks
less(NDArray, object)
Return (x1 < x2) element-wise with scalar.
public static NDArray<bool> less(NDArray x1, object x2)
Parameters
Returns
less(object, NDArray)
Return (x1 < x2) element-wise with scalar on left.
public static NDArray<bool> less(object x1, NDArray x2)
Parameters
Returns
less_equal(NDArray, NDArray, NDArray, NDArray, DType)
Return (x1 <= x2) element-wise.
Mirrors NumPy's ufunc signature: less_equal(x1, x2, /, out=None, *, where=True, dtype=None).
A plain call returns a bool-dtype array (the instance is an NDArray<TDType> of bool —
cast or use the <= operator for the typed wrapper).
public static NDArray less_equal(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayInput array.
x2NDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): comparisons have bool loops only — any non-bool request raises the no-loop TypeError.
Returns
Remarks
less_equal(NDArray, object)
Return (x1 <= x2) element-wise with scalar.
public static NDArray<bool> less_equal(NDArray x1, object x2)
Parameters
Returns
less_equal(object, NDArray)
Return (x1 <= x2) element-wise with scalar on left.
public static NDArray<bool> less_equal(object x1, NDArray x2)
Parameters
Returns
lexsort(NDArray, int)
np.lexsort with the keys packed in ONE array, exactly as NumPy reads it as a
sequence: a (k, …) array contributes its k SUB-ARRAYS as the keys (last row = primary).
A 1-D input therefore degenerates into N scalar (0-d) keys and returns the 0-d
0 — NumPy's probed quirk, not an error.
public static NDArray lexsort(NDArray keys, int axis = -1)
Parameters
keysNDArrayArray whose first-axis sub-arrays are the sort keys.
axisintAxis to sort along (default -1).
Returns
Remarks
lexsort(NDArray[], int)
Perform an indirect stable sort using a sequence of keys — the LAST key is the
PRIMARY sort key, the second-to-last breaks its ties, and so on (NumPy
np.lexsort). Returns int64 indices that sort every key line lexicographically.
public static NDArray lexsort(NDArray[] keys, int axis = -1)
Parameters
keysNDArray[]The k sort keys, all the same shape. Keys are only read.
axisintAxis to sort along (default -1, the last axis).
Returns
- NDArray
int64 index array of the keys' shape.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.lexsort.html
Port of PyArray_LexSort (item_selection.c): each key is run through a STABLE
argsort from FIRST to LAST, every pass re-sorting the running permutation — NumSharp's
radix argsort is stable, so the composition
perm = take_along_axis(perm, argsort(take_along_axis(key, perm))) reproduces
NumPy's mechanism pass for pass. Validation order is NumPy's: non-empty keys
(TypeError "need sequence of keys with len > 0 in lexsort") → same shape
(ValueError "all keys need to be the same shape") → axis bounds (0-d keys let axis
0/-1 slip through, NumPy's backwards-compat quirk) → the size ≤ 1 early return
(a 0-filled int64 array of the keys' shape). NaN keys sort last (stable argsort policy);
ties across ALL keys keep ascending index order.
linspace(double, double, int, bool, DType, string)
public static NDArray linspace(double start, double stop, int num, bool endpoint = true, DType dtype = null, string device = null)
Parameters
Returns
linspace(double, double, long, bool, DType, string)
public static NDArray linspace(double start, double stop, long num, bool endpoint = true, DType dtype = null, string device = null)
Parameters
Returns
linspace(float, float, int, bool, DType)
public static NDArray linspace(float start, float stop, int num, bool endpoint = true, DType dtype = null)
Parameters
Returns
linspace(float, float, long, bool, DType)
public static NDArray linspace(float start, float stop, long num, bool endpoint = true, DType dtype = null)
Parameters
Returns
load(byte[], string, bool, bool, string, long)
Load an array or archive from an in-memory .npy/.npz image.
public static object load(byte[] bytes, string mmap_mode = null, bool allow_pickle = false, bool fix_imports = true, string encoding = "ASCII", long max_header_size = 10000)
Parameters
bytesbyte[]mmap_modestringMemory-map mode for a
.npyfile:"r"/"readonly"(read-only),"r+"(read-write, flushed to disk) or"c"(copy-on-write, not flushed); null (default) reads the whole array into owned memory. Ignored for a.npzarchive, as in NumPy. Requires a file path — a stream or byte[] cannot be mapped. See OpenMemmap(string, string, long).allow_pickleboolWhether to trust the file. Default false, as in NumPy since 1.16.3: an object array is a Python pickle, and unpickling untrusted data can execute arbitrary code. NumSharp cannot unpickle at all, so this only selects the error message — and, per NumPy, lifts
max_header_size.fix_importsboolPresent for NumPy parity. Only affects unpickling Python 2 files, which NumSharp does not do.
encodingstringPresent for NumPy parity; validated but otherwise unused. Must be
"ASCII","latin1"or"bytes".max_header_sizelongReject headers larger than this (default 10000). Guards against a header crafted to make parsing pathologically expensive. Ignored when
allow_pickleis true.
Returns
- object
An NDArray for a
.npyfile, or an NpzFile for a.npzarchive — mirroring NumPy, whose return type also depends on the content. Prefer load_npy(string, bool, long) or load_npz(string, bool, long) when the kind is known: they are typed and need no cast.An NpzFile owns a file handle and must be disposed.
Examples
var arr = (NDArray)np.load("data.npy");
if (np.load("data.npz") is NpzFile npz)
using (npz)
{ NDArray w = npz["weights"]; }
Remarks
Exceptions
- EndOfStreamException
The file is empty.
- FormatException
The content is not a .npy or .npz file, or is malformed.
load(Stream, string, bool, bool, string, long)
Load an array or archive from an open stream. The stream must be readable and seekable, and is left open — the caller owns it.
public static object load(Stream file, string mmap_mode = null, bool allow_pickle = false, bool fix_imports = true, string encoding = "ASCII", long max_header_size = 10000)
Parameters
fileStreamPath to the file. The type is detected from its magic bytes, not its extension.
mmap_modestringMemory-map mode for a
.npyfile:"r"/"readonly"(read-only),"r+"(read-write, flushed to disk) or"c"(copy-on-write, not flushed); null (default) reads the whole array into owned memory. Ignored for a.npzarchive, as in NumPy. Requires a file path — a stream or byte[] cannot be mapped. See OpenMemmap(string, string, long).allow_pickleboolWhether to trust the file. Default false, as in NumPy since 1.16.3: an object array is a Python pickle, and unpickling untrusted data can execute arbitrary code. NumSharp cannot unpickle at all, so this only selects the error message — and, per NumPy, lifts
max_header_size.fix_importsboolPresent for NumPy parity. Only affects unpickling Python 2 files, which NumSharp does not do.
encodingstringPresent for NumPy parity; validated but otherwise unused. Must be
"ASCII","latin1"or"bytes".max_header_sizelongReject headers larger than this (default 10000). Guards against a header crafted to make parsing pathologically expensive. Ignored when
allow_pickleis true.
Returns
- object
An NDArray for a
.npyfile, or an NpzFile for a.npzarchive — mirroring NumPy, whose return type also depends on the content. Prefer load_npy(string, bool, long) or load_npz(string, bool, long) when the kind is known: they are typed and need no cast.An NpzFile owns a file handle and must be disposed.
Examples
var arr = (NDArray)np.load("data.npy");
if (np.load("data.npz") is NpzFile npz)
using (npz)
{ NDArray w = npz["weights"]; }
Remarks
Exceptions
- EndOfStreamException
The file is empty.
- FormatException
The content is not a .npy or .npz file, or is malformed.
load(string, string, bool, bool, string, long)
Load an array or archive from a .npy or .npz file.
public static object load(string file, string mmap_mode = null, bool allow_pickle = false, bool fix_imports = true, string encoding = "ASCII", long max_header_size = 10000)
Parameters
filestringPath to the file. The type is detected from its magic bytes, not its extension.
mmap_modestringMemory-map mode for a
.npyfile:"r"/"readonly"(read-only),"r+"(read-write, flushed to disk) or"c"(copy-on-write, not flushed); null (default) reads the whole array into owned memory. Ignored for a.npzarchive, as in NumPy. Requires a file path — a stream or byte[] cannot be mapped. See OpenMemmap(string, string, long).allow_pickleboolWhether to trust the file. Default false, as in NumPy since 1.16.3: an object array is a Python pickle, and unpickling untrusted data can execute arbitrary code. NumSharp cannot unpickle at all, so this only selects the error message — and, per NumPy, lifts
max_header_size.fix_importsboolPresent for NumPy parity. Only affects unpickling Python 2 files, which NumSharp does not do.
encodingstringPresent for NumPy parity; validated but otherwise unused. Must be
"ASCII","latin1"or"bytes".max_header_sizelongReject headers larger than this (default 10000). Guards against a header crafted to make parsing pathologically expensive. Ignored when
allow_pickleis true.
Returns
- object
An NDArray for a
.npyfile, or an NpzFile for a.npzarchive — mirroring NumPy, whose return type also depends on the content. Prefer load_npy(string, bool, long) or load_npz(string, bool, long) when the kind is known: they are typed and need no cast.An NpzFile owns a file handle and must be disposed.
Examples
var arr = (NDArray)np.load("data.npy");
if (np.load("data.npz") is NpzFile npz)
using (npz)
{ NDArray w = npz["weights"]; }
Remarks
Exceptions
- EndOfStreamException
The file is empty.
- FormatException
The content is not a .npy or .npz file, or is malformed.
load_npy(byte[], bool, long)
Load a single array from an in-memory .npy image.
public static NDArray load_npy(byte[] bytes, bool allow_pickle = false, long max_header_size = 10000)
Parameters
bytesbyte[]allow_pickleboolWhether the file is trusted; see load(string, string, bool, bool, string, long).
max_header_sizelongReject headers larger than this.
Returns
Exceptions
- FormatException
The file is not a .npy file, or is malformed.
load_npy(Stream, bool, long)
Read one array from a stream positioned at a .npy magic string. The stream is left
just past that array's data, so successive calls read successively saved arrays.
public static NDArray load_npy(Stream file, bool allow_pickle = false, long max_header_size = 10000)
Parameters
fileStreamAn open, readable stream.
allow_pickleboolWhether the file is trusted.
max_header_sizelongReject headers larger than this.
Returns
Exceptions
- EndOfStreamException
The stream is already at its end.
load_npy(string, bool, long)
Load a single array from a .npy file — load(string, string, bool, bool, string, long)
without the cast.
public static NDArray load_npy(string file, bool allow_pickle = false, long max_header_size = 10000)
Parameters
filestringPath to a
.npyfile.allow_pickleboolWhether the file is trusted; see load(string, string, bool, bool, string, long).
max_header_sizelongReject headers larger than this.
Returns
Exceptions
- FormatException
The file is not a .npy file, or is malformed.
load_npz(byte[], bool, long)
Open a .npz archive from an in-memory image.
public static NpzFile load_npz(byte[] bytes, bool allow_pickle = false, long max_header_size = 10000)
Parameters
bytesbyte[]allow_pickleboolWhether members are trusted.
max_header_sizelongReject member headers larger than this.
Returns
- NpzFile
A lazily-loading, dictionary-like archive. It holds an open file handle — dispose it:
using var npz = np.load_npz("m.npz");
Exceptions
- FormatException
The file is not a ZIP archive.
load_npz(Stream, bool, bool, long)
Open a .npz archive over a stream.
public static NpzFile load_npz(Stream file, bool own_stream = false, bool allow_pickle = false, long max_header_size = 10000)
Parameters
fileStreamA readable, seekable stream.
own_streamboolWhen true, disposing the archive also disposes the stream.
allow_pickleboolWhether members are trusted.
max_header_sizelongReject member headers larger than this.
Returns
load_npz(string, bool, long)
Open a .npz archive — load(string, string, bool, bool, string, long)
without the cast.
public static NpzFile load_npz(string file, bool allow_pickle = false, long max_header_size = 10000)
Parameters
filestringPath to a
.npzarchive.allow_pickleboolWhether members are trusted.
max_header_sizelongReject member headers larger than this.
Returns
- NpzFile
A lazily-loading, dictionary-like archive. It holds an open file handle — dispose it:
using var npz = np.load_npz("m.npz");
Exceptions
- FormatException
The file is not a ZIP archive.
loadtxt(IEnumerable<string>, DType, string, string, object, int, int[], bool, int, int?, string)
Load data from a sequence of lines (each string is one or more newline-separated lines).
public static NDArray loadtxt(IEnumerable<string> lines, DType dtype = null, string comments = "#", string delimiter = null, object converters = null, int skiprows = 0, int[] usecols = null, bool unpack = false, int ndmin = 0, int? max_rows = null, string quotechar = null)
Parameters
linesIEnumerable<string>dtypeDTypeElement type of the result (default double).
commentsstringString marking the start of a comment (rest of the line ignored); a multi-character string is stripped from each line.
nulldisables comments.delimiterstringColumn separator.
null(default) splits on runs of whitespace; otherwise a single character.convertersobjectPer-field parser(s): a Func<T, TResult> applied to every column, or an IDictionary<TKey, TValue> mapping a column index to a parser.
nulluses the dtype's parser.skiprowsintSkip this many leading lines (including comments/blanks).
usecolsint[]Which columns to read (0-based, negatives count from the end).
nullreads all.unpackboolIf true, transpose the result so columns can be unpacked as separate arrays.
ndminintMinimum dimensions of the result (0, 1 or 2); otherwise size-1 axes are squeezed.
max_rowsint?Read at most this many data rows after
skiprows(blank/comment lines don't count).quotecharstringQuote character; delimiters and comments inside a quoted field are literal.
nulldisables quoting.
Returns
Remarks
Parity with NumPy 2.4.2's np.loadtxt. Reads back what savetxt(string, NDArray, string, string, string, string, string, string, string) writes.
https://numpy.org/doc/stable/reference/generated/numpy.loadtxt.html
loadtxt(Stream, DType, string, string, object, int, int[], bool, int, string, int?, string)
Load data from an open text Stream (read from the current position; left open).
public static NDArray loadtxt(Stream stream, DType dtype = null, string comments = "#", string delimiter = null, object converters = null, int skiprows = 0, int[] usecols = null, bool unpack = false, int ndmin = 0, string encoding = null, int? max_rows = null, string quotechar = null)
Parameters
streamStreamdtypeDTypeElement type of the result (default double).
commentsstringString marking the start of a comment (rest of the line ignored); a multi-character string is stripped from each line.
nulldisables comments.delimiterstringColumn separator.
null(default) splits on runs of whitespace; otherwise a single character.convertersobjectPer-field parser(s): a Func<T, TResult> applied to every column, or an IDictionary<TKey, TValue> mapping a column index to a parser.
nulluses the dtype's parser.skiprowsintSkip this many leading lines (including comments/blanks).
usecolsint[]Which columns to read (0-based, negatives count from the end).
nullreads all.unpackboolIf true, transpose the result so columns can be unpacked as separate arrays.
ndminintMinimum dimensions of the result (0, 1 or 2); otherwise size-1 axes are squeezed.
encodingstringText encoding used to decode the file (default UTF-8).
max_rowsint?Read at most this many data rows after
skiprows(blank/comment lines don't count).quotecharstringQuote character; delimiters and comments inside a quoted field are literal.
nulldisables quoting.
Returns
Remarks
Parity with NumPy 2.4.2's np.loadtxt. Reads back what savetxt(string, NDArray, string, string, string, string, string, string, string) writes.
https://numpy.org/doc/stable/reference/generated/numpy.loadtxt.html
loadtxt(TextReader, DType, string, string, object, int, int[], bool, int, int?, string)
Load data from an open TextReader (left open).
public static NDArray loadtxt(TextReader reader, DType dtype = null, string comments = "#", string delimiter = null, object converters = null, int skiprows = 0, int[] usecols = null, bool unpack = false, int ndmin = 0, int? max_rows = null, string quotechar = null)
Parameters
readerTextReaderdtypeDTypeElement type of the result (default double).
commentsstringString marking the start of a comment (rest of the line ignored); a multi-character string is stripped from each line.
nulldisables comments.delimiterstringColumn separator.
null(default) splits on runs of whitespace; otherwise a single character.convertersobjectPer-field parser(s): a Func<T, TResult> applied to every column, or an IDictionary<TKey, TValue> mapping a column index to a parser.
nulluses the dtype's parser.skiprowsintSkip this many leading lines (including comments/blanks).
usecolsint[]Which columns to read (0-based, negatives count from the end).
nullreads all.unpackboolIf true, transpose the result so columns can be unpacked as separate arrays.
ndminintMinimum dimensions of the result (0, 1 or 2); otherwise size-1 axes are squeezed.
max_rowsint?Read at most this many data rows after
skiprows(blank/comment lines don't count).quotecharstringQuote character; delimiters and comments inside a quoted field are literal.
nulldisables quoting.
Returns
Remarks
Parity with NumPy 2.4.2's np.loadtxt. Reads back what savetxt(string, NDArray, string, string, string, string, string, string, string) writes.
https://numpy.org/doc/stable/reference/generated/numpy.loadtxt.html
loadtxt(string, DType, string, string, object, int, int[], bool, int, string, int?, string)
Load data from a text file into a 1-D or 2-D array.
public static NDArray loadtxt(string fname, DType dtype = null, string comments = "#", string delimiter = null, object converters = null, int skiprows = 0, int[] usecols = null, bool unpack = false, int ndmin = 0, string encoding = null, int? max_rows = null, string quotechar = null)
Parameters
fnamestringPath to the file; a
.gzname is transparently decompressed.dtypeDTypeElement type of the result (default double).
commentsstringString marking the start of a comment (rest of the line ignored); a multi-character string is stripped from each line.
nulldisables comments.delimiterstringColumn separator.
null(default) splits on runs of whitespace; otherwise a single character.convertersobjectPer-field parser(s): a Func<T, TResult> applied to every column, or an IDictionary<TKey, TValue> mapping a column index to a parser.
nulluses the dtype's parser.skiprowsintSkip this many leading lines (including comments/blanks).
usecolsint[]Which columns to read (0-based, negatives count from the end).
nullreads all.unpackboolIf true, transpose the result so columns can be unpacked as separate arrays.
ndminintMinimum dimensions of the result (0, 1 or 2); otherwise size-1 axes are squeezed.
encodingstringText encoding used to decode the file (default UTF-8).
max_rowsint?Read at most this many data rows after
skiprows(blank/comment lines don't count).quotecharstringQuote character; delimiters and comments inside a quoted field are literal.
nulldisables quoting.
Returns
Remarks
Parity with NumPy 2.4.2's np.loadtxt. Reads back what savetxt(string, NDArray, string, string, string, string, string, string, string) writes.
https://numpy.org/doc/stable/reference/generated/numpy.loadtxt.html
log(NDArray)
Natural logarithm, element-wise. The natural logarithm log is the inverse of the exponential function, so that log(exp(x)) = x. The natural logarithm is logarithm in base e.
public static NDArray log(NDArray x)
Parameters
xNDArrayInput value.
Returns
- NDArray
The natural logarithm of x, element-wise. This is a scalar if x is a scalar.
Remarks
log(NDArray, NDArray, NDArray, DType)
Natural logarithm, element-wise.
Mirrors NumPy's ufunc signature: log(x, /, out=None, *, where=True, dtype=None).
public static NDArray log(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput value.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs at this precision; integer/bool requests raise NumPy's "No loop matching" error.
Returns
Remarks
log10(NDArray)
Return the base 10 logarithm of the input array, element-wise.
public static NDArray log10(NDArray x)
Parameters
xNDArrayInput value.
Returns
- NDArray
The logarithm to the base 10 of x, element-wise. NaNs are returned where x is negative. This is a scalar if x is a scalar.
Remarks
log10(NDArray, NDArray, NDArray, DType)
Return the base 10 logarithm of the input array, element-wise.
public static NDArray log10(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
- NDArray
The logarithm to the base 10 of x, element-wise. NaNs are returned where x is negative. This is a scalar if x is a scalar.
Remarks
log1p(NDArray)
Return the natural logarithm of one plus the input array, element-wise.
Calculates log(1 + x).
public static NDArray log1p(NDArray x)
Parameters
xNDArrayInput value.
Returns
- NDArray
Natural logarithm of 1 + x, element-wise. This is a scalar if x is a scalar.
Remarks
log1p(NDArray, NDArray, NDArray, DType)
Return the natural logarithm of one plus the input array, element-wise.
Calculates log(1 + x).
public static NDArray log1p(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
- NDArray
Natural logarithm of 1 + x, element-wise. This is a scalar if x is a scalar.
Remarks
log2(NDArray)
Base-2 logarithm of x.
public static NDArray log2(NDArray x)
Parameters
xNDArrayInput value.
Returns
- NDArray
Base-2 logarithm of x. This is a scalar if x is a scalar.
Remarks
log2(NDArray, NDArray, NDArray, DType)
Base-2 logarithm of x.
public static NDArray log2(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
- NDArray
Base-2 logarithm of x. This is a scalar if x is a scalar.
Remarks
logaddexp(NDArray, NDArray, NDArray, NDArray, DType)
Logarithm of the sum of exponentiations of the inputs.
Calculates log(exp(x1) + exp(x2)), element-wise, without overflow/underflow —
the stable way to add probabilities held as logarithms.
Mirrors NumPy's ufunc signature: logaddexp(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray logaddexp(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayFirst input array (a log-domain value).
x2NDArraySecond input array. If shapes differ they must broadcast to a common shape.
outNDArrayA location into which the result is stored (joins the broadcast without being stretched, same_kind-castable from the loop dtype; returned as-is).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (float-family only; int/bool/complex raise NumPy's "No loop matching" error).
Returns
- NDArray
log(exp(x1) + exp(x2)). This is a scalar if both x1 and x2 are scalars.
Remarks
logaddexp2(NDArray, NDArray, NDArray, NDArray, DType)
Logarithm of the sum of exponentiations of the inputs in base-2.
Calculates log2(2x1 + 2x2), element-wise — the base-2 analogue of
logaddexp(NDArray,NDArray,NDArray,NDArray,NPTypeCode?), useful in machine
learning when the calculated probabilities are expressed in base-2.
Mirrors NumPy's ufunc signature: logaddexp2(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray logaddexp2(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayFirst input array (a log2-domain value).
x2NDArraySecond input array. If shapes differ they must broadcast to a common shape.
outNDArrayA location into which the result is stored (NumPy ufunc out=).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (float-family only).
Returns
- NDArray
log2(2x1 + 2x2). This is a scalar if both x1 and x2 are scalars.
Remarks
logical_and(NDArray, NDArray)
Compute the truth value of x1 AND x2 element-wise.
public static NDArray<bool> logical_and(NDArray x1, NDArray x2)
Parameters
Returns
- NDArray<bool>
Boolean result of the logical AND operation applied to the elements of x1 and x2; the shape is determined by broadcasting.
Remarks
logical_not(NDArray)
Compute the truth value of NOT x element-wise.
public static NDArray<bool> logical_not(NDArray x)
Parameters
xNDArrayLogical NOT is applied to the elements of x.
Returns
Remarks
logical_or(NDArray, NDArray)
Compute the truth value of x1 OR x2 element-wise.
public static NDArray<bool> logical_or(NDArray x1, NDArray x2)
Parameters
Returns
- NDArray<bool>
Boolean result of the logical OR operation applied to the elements of x1 and x2; the shape is determined by broadcasting.
Remarks
logical_xor(NDArray, NDArray)
Compute the truth value of x1 XOR x2 element-wise.
public static NDArray<bool> logical_xor(NDArray x1, NDArray x2)
Parameters
Returns
- NDArray<bool>
Boolean result of the logical XOR operation applied to the elements of x1 and x2; the shape is determined by broadcasting.
Remarks
mask_indices(int, Func<NDArray, int, NDArray>, int)
Return the indices to access (n, n) arrays, given a masking function.
public static NDArray<long>[] mask_indices(int n, Func<NDArray, int, NDArray> mask_func, int k = 0)
Parameters
nintThe returned indices will be valid to access arrays of shape
(n, n).mask_funcFunc<NDArray, int, NDArray>A function whose call signature is
(arr, k)and which returnsn-by-nmasked arrays — e.g. triu(NDArray, int) or tril(NDArray, int).kintAn optional argument passed through to
mask_func.
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.mask_indices.html
The returned arity follows mask_func's output rank, not
n: passing diag(NDArray, int) — which reduces a 2-D input to its 1-D
diagonal — yields a single index array, matching NumPy (probed).
matmul(NDArray, NDArray, NDArray, int[][], int?, bool?, DType, string, char)
Matrix product of two arrays — the gufunc (n?,k),(k,m?)->(n?,m?), with NumPy's
full keyword surface.
public static NDArray matmul(NDArray x1, NDArray x2, NDArray @out = null, int[][] axes = null, int? axis = null, bool? keepdims = null, DType dtype = null, string casting = "same_kind", char order = 'K')
Parameters
x1NDArrayLhs input array, scalars not allowed.
x2NDArrayRhs input array, scalars not allowed.
outNDArrayWhere to deposit the answer; returned as-is when given. Like a ufunc's
out(and unlike dot(NDArray, NDArray, NDArray)'s strict one) it may be strided and takes a cast from the product dtype undercasting.axesint[][]Which axes carry the core dimensions, per operand:
{x1, x2, out}. A 2-D operand names TWO axes, a 1-D operand ONE (its optional core dim is absent); the output entry may be omitted only for the 1-D·1-D product, whose result has no core axes. Cannot be combined withaxis.axisint?Present for signature parity only. NumPy raises
TypeErrorfor any value, becausematmul's signature has three DISTINCT core dimensions — useaxes.keepdimsbool?Present for signature parity only. NumPy raises
TypeErrorfor ANY value (True OR False), because its output has core dimensions. Modelled with abool?sentinel so that, like NumPy'snp._NoValuedefault, an explicitfalsealso rejects.dtypeDTypeSelects the LOOP: the product runs at this dtype, not merely the result.
castingstringCasting rule (default
"same_kind", the ufunc default) gating BOTH the input→loop cast adtypeforces and the product→outcast.ordercharMemory layout of the result —
'C','F','A'or'K'.
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.matmul.html
The product itself is unchanged — TensorEngine.Matmul, which routes
float32/float64/complex128 through OpenBLAS when NumSharp.Interop.OpenBLAS is
referenced (byte-identical to NumPy) and through the managed GEMM otherwise. A
dtype request is applied by casting the operands to that dtype BEFORE
the product, so the loop — and thus the backend route — follows it.
Like the five sibling product gufuncs, NumPy's remaining ufunc keywords subok and
signature are not modelled (signature is what dtype
does; subok concerns ndarray subclasses NumSharp does not have). A
out with a wrong CORE dim reports NumPy's verbatim core-dimension
message; extra leading LOOP dims broadcast (replicating the product, as NumPy does), and
the rarer genuine loop-dimension mismatch raises copyto's broadcast
ValueError whose wording differs from NumPy's leaked iterator text (the same
latitude the siblings take).
matrix_transpose(NDArray)
Transposes a matrix (or a stack of matrices) x.
Swaps the two innermost dimensions, i.e. an array of shape (..., M, N) becomes (..., N, M).
Equivalent to np.swapaxes(x, -1, -2). This function is Array API compatible.
public static NDArray matrix_transpose(NDArray x)
Parameters
xNDArrayInput array having shape
(..., M, N)and whose two innermost dimensions formMxNmatrices.
Returns
- NDArray
An array containing the transpose for each matrix and having shape
(..., N, M). A view is returned whenever possible.
Remarks
Exceptions
- ArgumentException
If
xhas fewer than 2 dimensions.
matvec(NDArray, NDArray, NDArray, int[][], int?, bool, DType)
Matrix-vector product (NumPy 2.2) — the gufunc (m,n),(n)->(m), NumPy's
gemv route.
public static NDArray matvec(NDArray x1, NDArray x2, NDArray @out = null, int[][] axes = null, int? axis = null, bool keepdims = false, DType dtype = null)
Parameters
x1NDArrayMatrix operand, at least 2-D. Leading axes broadcast.
x2NDArrayVector operand, at least 1-D. NOT conjugated.
outNDArrayWhere to deposit the answer. Returned as-is when given.
axesint[][]Which axes carry the core dimensions, per operand:
{(m,n), (n), (m)}. All THREE entries are required — the output has a core axis, so its entry cannot be omitted the way vecdot(NDArray, NDArray, NDArray, int[][], int?, bool, DType)'s can.axisint?Present for signature parity only. NumPy raises
TypeErrorfor any value, because this signature's core dimensions are two DISTINCT ones — useaxes.keepdimsboolPresent for signature parity only. NumPy raises
TypeErrorwhen true, for the same reason.dtypeDTypeSelects the LOOP: computation runs at this dtype, not merely the result.
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.matvec.html
This differs from matmul(x1, x2) with a 1-D x2 in how it BROADCASTS:
matmul treats a 1-D second operand as a one-off shape promotion, while
matvec is a true gufunc whose vector operand carries its own leading axes.
Unlike vecmat(NDArray, NDArray, NDArray, int[][], int?, bool, DType) it does not conjugate — the transformation, not the inner
product, is what this computes.
NumPy's remaining ufunc keywords (casting, order, subok,
signature) are not modelled anywhere in NumSharp's ufunc surface and are
absent here too. See vecdot(NDArray, NDArray, NDArray, int[][], int?, bool, DType).
max(NDArray, int?, bool, DType)
Return the maximum of an array or maximum along an axis.
public static NDArray max(NDArray a, int? axis = null, bool keepdims = false, DType dtype = null)
Parameters
aNDArrayaxisint?Axis or axes along which to operate.
keepdimsboolIf 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.
dtypeDTypethe 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
maximum(NDArray, NDArray, DType)
Element-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then that element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated.
public static NDArray maximum(NDArray x1, NDArray x2, DType dtype = null)
Parameters
x1NDArrayThe arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
x2NDArrayThe arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
dtypeDTypeLoop dtype (NumPy ufunc dtype=): the comparison runs at this precision.
Returns
- NDArray
The maximum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.
maximum(NDArray, NDArray, NDArray)
Element-wise maximum of array elements (NaN-propagating), writing into @out.
public static NDArray maximum(NDArray x1, NDArray x2, NDArray @out)
Parameters
Returns
maximum_sctype(NPTypeCode)
Return the scalar type of highest precision of the same kind as the input.
public static DType maximum_sctype(NPTypeCode t)
Parameters
tNPTypeCodeThe input scalar type.
Returns
- DType
The highest precision type of the same kind.
Examples
np.maximum_sctype(NPTypeCode.Int32) // Int64
np.maximum_sctype(NPTypeCode.Single) // Double (or Decimal)
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.maximum_sctype.html
Uses NPTypeHierarchy for consistent type categorization across all typing functions.
mean(NDArray)
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 static NDArray mean(NDArray a)
Parameters
aNDArrayArray containing numbers whose mean is desired. If a is not an array, a conversion is attempted.
Returns
- NDArray
returns a new array containing the mean values, otherwise a reference to the output array is returned.
Remarks
mean(NDArray, 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 static NDArray mean(NDArray a, bool keepdims)
Parameters
aNDArrayArray containing numbers whose mean is desired. If a is not an array, a conversion is attempted.
keepdimsboolIf 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(NDArray, 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 static NDArray mean(NDArray a, int axis)
Parameters
aNDArrayArray containing numbers whose mean is desired. If a is not an array, a conversion is attempted.
axisintAxis 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(NDArray, 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 static NDArray mean(NDArray a, int axis, DType dtype, bool keepdims = false)
Parameters
aNDArrayArray containing numbers whose mean is desired. If a is not an array, a conversion is attempted.
axisintAxis or axes along which the means are computed. The default is to compute the mean of the flattened array.
dtypeDTypeType to use in computing the mean. For integer inputs, the default is float64; for floating point inputs, it is the same as the input dtype.
keepdimsboolIf 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(NDArray, 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 static NDArray mean(NDArray a, int axis, bool keepdims)
Parameters
aNDArrayArray containing numbers whose mean is desired. If a is not an array, a conversion is attempted.
axisintAxis or axes along which the means are computed. The default is to compute the mean of the flattened array.
keepdimsboolIf 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.
median(NDArray, int[], NDArray, bool, bool)
public static NDArray median(NDArray a, int[] axis, NDArray @out = null, bool overwrite_input = false, bool keepdims = false)
Parameters
Returns
median(NDArray, int?, NDArray, bool, bool)
Compute the median along the specified axis.
For an even-sized slice the median is the mean of the two central values;
for an odd-sized slice it is the single central value. Equivalent to
np.quantile(a, 0.5) for our purposes, which matches NumPy's contract.
public static NDArray median(NDArray a, int? axis = null, NDArray @out = null, bool overwrite_input = false, bool keepdims = false)
Parameters
Returns
Remarks
meshgrid(NDArray, NDArray, NDArray, string, bool, bool)
Return coordinate matrices from three coordinate vectors — see meshgrid(NDArray[], string, bool, bool).
public static np.MeshgridResult meshgrid(NDArray x1, NDArray x2, NDArray x3, string indexing = "xy", bool sparse = false, bool copy = true)
Parameters
Returns
meshgrid(NDArray, NDArray, string, bool, bool)
Return coordinate matrices from two coordinate vectors — see meshgrid(NDArray[], string, bool, bool).
public static np.MeshgridResult meshgrid(NDArray x1, NDArray x2, string indexing = "xy", bool sparse = false, bool copy = true)
Parameters
Returns
meshgrid(NDArray[], string, bool, bool)
Return a tuple of coordinate matrices from N coordinate vectors — make N-D coordinate arrays for vectorized evaluation of N-D fields over an N-D grid.
public static np.MeshgridResult meshgrid(NDArray[] xi, string indexing = "xy", bool sparse = false, bool copy = true)
Parameters
xiNDArray[]The coordinate vectors. Each is flattened to 1-D, so a higher-rank input is read in C-order. For the two- and three-vector cases the
x1, x2[, x3]overloads let them be passed directly (np.meshgrid(x, y)); use this overload for four or more.indexingstring"xy"(Cartesian, default) or"ij"(matrix). For two inputs of length M and N the outputs are(N, M)under"xy"and(M, N)under"ij"; the two conventions swap the first two axes. Has no effect for a single input.sparseboolIf true, grid
ikeeps the open-mesh shape(1, …, Ni, …, 1)instead of the full(N1, …, Nn)— these broadcast to the same dense result. Default false.copyboolIf true (default) each grid is an independent C-contiguous array. If false the dense grids are returned as broadcast VIEWS (non-contiguous, and multiple elements may alias one memory location — copy before writing).
Returns
- np.MeshgridResult
N grids as a np.MeshgridResult (NumPy's tuple): implicit to NDArray
[], deconstructable, and indexable.
Examples
var (xx, yy) = np.meshgrid(np.arange(3), np.arange(2)); // xx,yy shape (2,3), 'xy'
var (i, j) = np.meshgrid(a, b, indexing: "ij"); // shape (len a, len b)
NDArray[] g = np.meshgrid(a, b, sparse: true); // (1,M) and (N,1)
Remarks
Port of NumPy 2.x numpy.meshgrid (numpy/lib/_function_base_impl.py). Each input
is reshaped to its open-mesh axis; "xy" then swaps the placement of the first two;
unless sparse the grids are broadcast to the full shape; unless
copy is false they are then materialized. Each grid PRESERVES its input's
dtype (grids are not promoted to a common type). The companion open-mesh builder is
ix_(params object[]); the indexing-notation forms are mgrid / ogrid.
https://numpy.org/doc/stable/reference/generated/numpy.meshgrid.html
min(NDArray, int?, bool, DType)
Return the minimum of an array or minimum along an axis.
public static NDArray min(NDArray a, int? axis = null, bool keepdims = false, DType dtype = null)
Parameters
aNDArrayInput data.
axisint?Axis or axes along which to operate.
keepdimsboolIf 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.
dtypeDTypethe 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_scalar_type(object)
For scalar value, returns the data type with the smallest size and smallest scalar kind which can hold its value.
public static DType min_scalar_type(object value)
Parameters
valueobjectThe scalar value to check.
Returns
- DType
The minimum dtype that can represent the value.
Examples
np.min_scalar_type(10) // Byte (uint8)
np.min_scalar_type(-10) // SByte (int8)
np.min_scalar_type(1000) // UInt16
np.min_scalar_type(1.0) // Half (float16)
np.min_scalar_type(true) // Boolean
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.min_scalar_type.html
For integers, finds the smallest integer type that can hold the value. For floats, finds the smallest float type whose RANGE (magnitude) can hold the value — matching NumPy, precision loss is allowed (e.g. 1e-40 reports float16).
minimum(NDArray, NDArray, DType)
Element-wise minimum of array elements. Compare two arrays and returns a new array containing the element-wise minima. If one of the elements being compared is a NaN, then that element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated.
public static NDArray minimum(NDArray x1, NDArray x2, DType dtype = null)
Parameters
x1NDArrayThe arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
x2NDArrayThe arrays holding the elements to be compared. If x1.shape != x2.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
dtypeDTypeLoop dtype (NumPy ufunc dtype=): the comparison runs at this precision.
Returns
- NDArray
The minimum of x1 and x2, element-wise. This is a scalar if both x1 and x2 are scalars.
minimum(NDArray, NDArray, NDArray)
Element-wise minimum of array elements (NaN-propagating), writing into @out.
public static NDArray minimum(NDArray x1, NDArray x2, NDArray @out)
Parameters
Returns
mintypecode(char[], string, char)
Return the character for the minimum-size type to which given types can be safely cast. The returned type character must represent the smallest size dtype such that an array of the returned type can handle the data from an array of all types in typechars(or if typechars is an array, then its dtype.char).
public static char mintypecode(char[] typechars, string typeset = "GDFgdf", char @default = 'd')
Parameters
typecharschar[]typesetstringThe set of characters that the returned character is chosen from. The default set is ‘GDFgdf’.
defaultcharThe default character, this is returned if none of the characters in typechars matches a character in typeset.
Returns
- char
The character representing the minimum-size type that was found.
mintypecode(string, string, char)
Return the character for the minimum-size type to which given types can be safely cast. The returned type character must represent the smallest size dtype such that an array of the returned type can handle the data from an array of all types in typechars(or if typechars is an array, then its dtype.char).
public static char mintypecode(string typechars, string typeset = "GDFgdf", char @default = 'd')
Parameters
typecharsstringevery character represents a type. see char
typesetstringThe set of characters that the returned character is chosen from. The default set is ‘GDFgdf’.
defaultcharThe default character, this is returned if none of the characters in typechars matches a character in typeset.
Returns
- char
The character representing the minimum-size type that was found.
mod(NDArray, NDArray, NDArray, NDArray, DType)
public static NDArray mod(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
Remarks
mod(NDArray, float)
public static NDArray mod(NDArray x1, float x2)
Parameters
Returns
modf(NDArray, DType)
Return the fractional and integral parts of an array, element-wise. The fractional and integral parts are negative if the given number is negative.
public static (NDArray Fractional, NDArray Intergral) modf(NDArray x, DType dtype = null)
Parameters
xNDArrayInput array.
dtypeDTypeThe dtype the returned ndarray should be of, only non integer values are supported.
Returns
Remarks
moveaxis(NDArray, int, int)
Move axes of an array to new positions. Other axes remain in their original order.
public static NDArray moveaxis(NDArray a, int source, int destination)
Parameters
aNDArrayThe array whose axes should be reordered.
sourceintOriginal positions of the axes to move. These must be unique (distinct).
destinationintDestination positions for each of the original axes. These must also be unique (distinct).
Returns
- NDArray
Array with moved axes.
Remarks
moveaxis(NDArray, int, int[])
Move axes of an array to new positions. Other axes remain in their original order.
public static NDArray moveaxis(NDArray a, int source, int[] destination)
Parameters
aNDArrayThe array whose axes should be reordered.
sourceintOriginal positions of the axes to move. These must be unique (distinct).
destinationint[]Destination positions for each of the original axes. These must also be unique (distinct).
Returns
- NDArray
Array with moved axes.
Remarks
moveaxis(NDArray, int[], int)
Move axes of an array to new positions. Other axes remain in their original order.
public static NDArray moveaxis(NDArray a, int[] source, int destination)
Parameters
aNDArrayThe array whose axes should be reordered.
sourceint[]Original positions of the axes to move. These must be unique (distinct).
destinationintDestination positions for each of the original axes. These must also be unique (distinct).
Returns
- NDArray
Array with moved axes.
Remarks
moveaxis(NDArray, int[], int[])
Move axes of an array to new positions. Other axes remain in their original order.
public static NDArray moveaxis(NDArray a, int[] source, int[] destination)
Parameters
aNDArrayThe array whose axes should be reordered.
sourceint[]Original positions of the axes to move. These must be unique (distinct).
destinationint[]Destination positions for each of the original axes. These must also be unique (distinct).
Returns
- NDArray
Array with moved axes.
Remarks
multiply(NDArray, NDArray, NDArray, NDArray, DType)
public static NDArray multiply(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
Remarks
multithreading(bool, int)
Enable or disable NumSharp's multithreaded kernels and cap the worker thread count.
public static void multithreading(bool enabled, int max_threads = 8)
Parameters
enabledboolWhether kernels are allowed to use more than one thread.
max_threadsintUpper bound on worker threads (clamped to at least 1 and to the processor count). Defaults to 8.
Remarks
Multithreading is disabled by default, so the default behavior — and the exact summation order — is unchanged unless you opt in.
Currently this controls the fused 1-D dot product (dot(NDArray,NDArray)
for vector·vector) on contiguous float / double inputs. Only large
vectors are parallelized; small and medium ones stay single-threaded because thread
fan-out would cost more than it saves. With multithreading on, the inner product is
summed per-chunk and combined, so results may differ from the single-threaded path in
the last few ULPs (the same floating-point reordering NumPy's threaded BLAS exhibits).
np.multithreading(true); // enable, up to 8 threads
np.multithreading(true, 16); // enable, up to 16 threads
np.multithreading(false); // back to single-threaded
This is a facade over TensorEngine.Threading: the thread cap is routed through
its NumSharp knob (so max_threads also writes the
process-scoped NUMSHARP_NUM_THREADS and is visible through that surface), while the
enable flag sets Enabled. Both are seeded at startup from
NUMSHARP_MULTITHREADING / NUMSHARP_NUM_THREADS as the source of truth.
nan_to_num(NDArray, bool, object, object, object)
Replace NaN with zero and infinity with large finite numbers (default behaviour) or with the
values supplied via nan, posinf and/or
neginf.
public static NDArray nan_to_num(NDArray x, bool copy = true, object nan = null, object posinf = null, object neginf = null)
Parameters
xNDArrayInput data.
copyboolWhether to create a copy of
x(true, the default) or replace values in place (false). Withfalsethe returned array may bexitself (writes go through to shared memory).nanobjectValue(s) used to fill NaN. A scalar (int/float/bool) or an array_like (NDArray or a C# array) broadcast position-wise.
null(default) fills NaN with0.0.posinfobjectValue(s) used to fill +Inf.
null(default) fills with the largest finite value representable byx's (real) dtype.neginfobjectValue(s) used to fill -Inf.
null(default) fills with the most negative finite value representable byx's (real) dtype.
Returns
- NDArray
xwith the non-finite values replaced. Ifcopy=falsethis may bexitself. Integer/boolean/decimal inputs are returned unchanged (a copy whencopy=true) — they are not inexact and hold no NaN/Inf.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nan_to_num.html
Port of NumPy's numpy.nan_to_num (numpy/lib/_type_check_impl.py). For a complex
input the replacement is applied to the real and imaginary components separately, both using the
float64 finfo limits (matching NumPy). The common contiguous scalar-fill case runs a
single fused whole-array kernel (NanToNum(NPTypeCode, void*, void*, long, void*, void*, void*)) — one read + one
write, no intermediate allocation — instead of NumPy's isnan/isposinf/isneginf + three
copyto(where=) passes. Array-valued fills and non-contiguous in-place targets take the
faithful copyto composition.
nanargmax(NDArray)
Return the index of the maximum value in the flattened array, ignoring NaNs. For an all-NaN array a ValueError is raised. Warning: the result cannot be trusted if the array contains only NaNs and -Infs (NumPy caveat).
public static long nanargmax(NDArray a)
Parameters
aNDArrayInput data.
Returns
- long
Index of the maximum value in the flattened array (NumPy intp = int64).
Remarks
Exceptions
- ValueError
All-NaN slice encountered.
nanargmax(NDArray, int?, NDArray, bool)
Return the indices of the maximum values in the specified axis, ignoring NaNs. For all-NaN slices a ValueError is raised. Warning: the results cannot be trusted if a slice contains only NaNs and -Infs (NumPy caveat).
public static NDArray nanargmax(NDArray a, int? axis = null, NDArray @out = null, bool keepdims = false)
Parameters
aNDArrayInput data.
axisint?Axis along which to operate. If
null, the flattened input is used.outNDArrayIf provided, the result is inserted into this array and the SAME instance is returned (NumPy semantics): the shape must equal the result's exactly, and the dtype must be an integer family safe-castable to int64 (bool through uint32 — uint64/floats raise NumPy's verbatim cast TypeError); the int64 indices then cast UNSAFELY into it (wrap/truncate).
keepdimsboolIf true, the reduced axes are left in the result as dimensions with size one (with
axisnullthe result has shape(1,) * a.ndim, like NumPy).
Returns
- NDArray
Array of int64 indices (or a 0-d scalar for the flattened form);
outwhen given.
Remarks
Exceptions
- ValueError
All-NaN slice encountered.
- AxisError
Axis out of bounds (reports the original axis, like NumPy).
nanargmin(NDArray)
Return the index of the minimum value in the flattened array, ignoring NaNs. For an all-NaN array a ValueError is raised. Warning: the result cannot be trusted if the array contains only NaNs and Infs (NumPy caveat).
public static long nanargmin(NDArray a)
Parameters
aNDArrayInput data.
Returns
- long
Index of the minimum value in the flattened array (NumPy intp = int64).
Remarks
Exceptions
- ValueError
All-NaN slice encountered.
nanargmin(NDArray, int?, NDArray, bool)
Return the indices of the minimum values in the specified axis, ignoring NaNs. For all-NaN slices a ValueError is raised. Warning: the results cannot be trusted if a slice contains only NaNs and Infs (NumPy caveat).
public static NDArray nanargmin(NDArray a, int? axis = null, NDArray @out = null, bool keepdims = false)
Parameters
aNDArrayInput data.
axisint?Axis along which to operate. If
null, the flattened input is used.outNDArrayIf provided, the result is inserted into this array and the SAME instance is returned (NumPy semantics — see nanargmax(NDArray, int?, NDArray, bool)).
keepdimsboolIf true, the reduced axes are left in the result as dimensions with size one (with
axisnullthe result has shape(1,) * a.ndim, like NumPy).
Returns
- NDArray
Array of int64 indices (or a 0-d scalar for the flattened form);
outwhen given.
Remarks
Exceptions
- ValueError
All-NaN slice encountered.
- AxisError
Axis out of bounds (reports the original axis, like NumPy).
nancumprod(NDArray, int?, DType, NDArray)
Return the cumulative product of array elements over a given axis treating Not a Numbers (NaNs) as one. The cumulative product does not change when NaNs are encountered and leading NaNs are replaced by ones. Ones are returned for slices that are all-NaN or empty.
public static NDArray nancumprod(NDArray a, int? axis = null, DType dtype = null, NDArray @out = null)
Parameters
aNDArrayInput array.
axisint?Axis along which the cumulative product is computed. The default (None) is to compute the cumprod over the flattened array.
dtypeDTypeType of the returned array and of the accumulator in which the elements are multiplied (a Type, NPTypeCode, dtype string or DType — all convert implicitly). If not specified, it defaults to the dtype of
a, unlessahas an integer dtype with a precision less than that of the default platform integer, in which case the default platform integer is used.outNDArrayAlternate output array in which to place the result. It must have the same shape and buffer length as the expected output, but its dtype may differ (the result is cast into it with NumPy's unsafe casting) and a reference to
outis returned.
Returns
- NDArray
A new array holding the result unless
outis specified, in which case a reference tooutis returned.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nancumprod.html
Port of numpy/lib/_nanfunctions_impl.py::nancumprod: _replace_nan(a, 1) then np.cumprod.
Only float-family dtypes can contain NaN, so integer/bool/decimal inputs are equivalent to cumprod(NDArray, int?, DType, NDArray).
nancumsum(NDArray, int?, DType, NDArray)
Return the cumulative sum of array elements over a given axis treating Not a Numbers (NaNs) as zero. The cumulative sum does not change when NaNs are encountered and leading NaNs are replaced by zeros. Zeros are returned for slices that are all-NaN or empty.
public static NDArray nancumsum(NDArray a, int? axis = null, DType dtype = null, NDArray @out = null)
Parameters
aNDArrayInput array.
axisint?Axis along which the cumulative sum is computed. The default (None) is to compute the cumsum over the flattened array.
dtypeDTypeType of the returned array and of the accumulator in which the elements are summed (a Type, NPTypeCode, dtype string or DType — all convert implicitly). If not specified, it defaults to the dtype of
a, unlessahas an integer dtype with a precision less than that of the default platform integer, in which case the default platform integer is used.outNDArrayAlternate output array in which to place the result. It must have the same shape and buffer length as the expected output, but its dtype may differ (the result is cast into it with NumPy's unsafe casting) and a reference to
outis returned.
Returns
- NDArray
A new array holding the result unless
outis specified, in which case a reference tooutis returned. The result has the same size asa, and the same shape ifaxisis not None orais 1-D.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nancumsum.html
Port of numpy/lib/_nanfunctions_impl.py::nancumsum: _replace_nan(a, 0) then np.cumsum.
Only float-family dtypes can contain NaN, so integer/bool/decimal inputs are equivalent to cumsum(NDArray, int?, DType, NDArray).
nanmax(NDArray, int?, bool)
Return maximum of an array or maximum along an axis, ignoring any NaNs.
public static NDArray nanmax(NDArray a, int? axis = null, bool keepdims = false)
Parameters
aNDArrayArray containing numbers whose maximum is desired. If a is not an array, a conversion is attempted.
axisint?Axis or axes along which the maximum is computed. The default is to compute the maximum of the flattened array.
keepdimsboolIf this is set to True, the axes which are reduced are left in the result as dimensions with size one.
Returns
- NDArray
A new array containing the maximum. If all values are NaN, returns NaN.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanmax.html Only applicable to float and double arrays. For integer arrays, this is equivalent to np.amax (no NaN values possible).
nanmean(NDArray, int?, bool)
Compute the arithmetic mean along the specified axis, ignoring NaNs. 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 static NDArray nanmean(NDArray a, int? axis = null, bool keepdims = false)
Parameters
aNDArrayArray containing numbers whose mean is desired. If a is not an array, a conversion is attempted.
axisint?Axis or axes along which the means are computed. The default is to compute the mean of the flattened array.
keepdimsboolIf this is set to True, the axes which are reduced are left in the result as dimensions with size one.
Returns
- NDArray
A new array containing the mean values, with NaN values ignored. If all values along an axis are NaN, returns NaN for that slice.
Remarks
nanmedian(NDArray, int[], NDArray, bool, bool)
public static NDArray nanmedian(NDArray a, int[] axis, NDArray @out = null, bool overwrite_input = false, bool keepdims = false)
Parameters
Returns
nanmedian(NDArray, int?, NDArray, bool, bool)
Compute the median along the specified axis, ignoring NaNs.
Equivalent to np.nanquantile(a, 0.5). A slice that is entirely NaN
(or empty) yields NaN, matching NumPy's "All-NaN slice" behaviour.
public static NDArray nanmedian(NDArray a, int? axis = null, NDArray @out = null, bool overwrite_input = false, bool keepdims = false)
Parameters
Returns
Remarks
nanmin(NDArray, int?, bool)
Return minimum of an array or minimum along an axis, ignoring any NaNs.
public static NDArray nanmin(NDArray a, int? axis = null, bool keepdims = false)
Parameters
aNDArrayArray containing numbers whose minimum is desired. If a is not an array, a conversion is attempted.
axisint?Axis or axes along which the minimum is computed. The default is to compute the minimum of the flattened array.
keepdimsboolIf this is set to True, the axes which are reduced are left in the result as dimensions with size one.
Returns
- NDArray
A new array containing the minimum. If all values are NaN, returns NaN.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanmin.html Only applicable to float and double arrays. For integer arrays, this is equivalent to np.amin (no NaN values possible).
nanpercentile(NDArray, NDArray, int?, NDArray, bool, string, bool)
public static NDArray nanpercentile(NDArray a, NDArray q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)
Parameters
Returns
nanpercentile(NDArray, double, int[], NDArray, bool, string, bool)
public static NDArray nanpercentile(NDArray a, double q, int[] axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)
Parameters
Returns
nanpercentile(NDArray, double, int?, NDArray, bool, string, bool)
Compute the q-th percentile of the data along the specified axis, ignoring NaNs.
q must be in [0, 100]. Equivalent to np.nanquantile(a, q/100).
A slice that is entirely NaN (or empty) yields NaN.
public static NDArray nanpercentile(NDArray a, double q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)
Parameters
Returns
Remarks
nanpercentile(NDArray, double[], int[], NDArray, bool, string, bool)
public static NDArray nanpercentile(NDArray a, double[] q, int[] axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)
Parameters
Returns
nanpercentile(NDArray, double[], int?, NDArray, bool, string, bool)
public static NDArray nanpercentile(NDArray a, double[] q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)
Parameters
Returns
nanprod(NDArray, int?, bool)
Return the product of array elements over a given axis treating Not a Numbers (NaNs) as ones.
public static NDArray nanprod(NDArray a, int? axis = null, bool keepdims = false)
Parameters
aNDArrayArray containing numbers whose product is desired. If a is not an array, a conversion is attempted.
axisint?Axis or axes along which the product is computed. The default is to compute the product of the flattened array.
keepdimsboolIf this is set to True, the axes which are reduced are left in the result as dimensions with size one.
Returns
- NDArray
A new array containing the product, with NaN values treated as one.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nanprod.html Only applicable to float and double arrays. For integer arrays, this is equivalent to np.prod (no NaN values possible).
nanquantile(NDArray, NDArray, int?, NDArray, bool, string, bool)
NDArray-q overload — accepts a 0-D or 1-D NDArray of quantile values. Higher-rank q is rejected (NumPy raises "q must be a scalar or 1d").
public static NDArray nanquantile(NDArray a, NDArray q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)
Parameters
Returns
nanquantile(NDArray, double, int[], NDArray, bool, string, bool)
public static NDArray nanquantile(NDArray a, double q, int[] axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)
Parameters
Returns
nanquantile(NDArray, double, int?, NDArray, bool, string, bool)
Compute the q-th quantile of the data along the specified axis, ignoring NaNs.
q must be in the range [0, 1]. A slice that is entirely NaN
(or empty) yields NaN, matching NumPy's "All-NaN slice" behaviour.
public static NDArray nanquantile(NDArray a, double q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)
Parameters
Returns
Remarks
nanquantile(NDArray, double[], int[], NDArray, bool, string, bool)
public static NDArray nanquantile(NDArray a, double[] q, int[] axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)
Parameters
Returns
nanquantile(NDArray, double[], int?, NDArray, bool, string, bool)
public static NDArray nanquantile(NDArray a, double[] q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)
Parameters
Returns
nanstd(NDArray, int?, bool, int)
Compute the standard deviation along the specified axis, while ignoring NaNs. Returns the standard deviation, a measure of the spread of a distribution, of the non-NaN array elements. The standard deviation is computed for the flattened array by default, otherwise over the specified axis.
public static NDArray nanstd(NDArray a, int? axis = null, bool keepdims = false, int ddof = 0)
Parameters
aNDArrayCalculate the standard deviation of the non-NaN values.
axisint?Axis or axes along which the standard deviation is computed. The default is to compute the standard deviation of the flattened array.
keepdimsboolIf this is set to True, the axes which are reduced are left in the result as dimensions with size one.
ddofintMeans Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of non-NaN elements. By default ddof is zero.
Returns
- NDArray
A new array containing the standard deviation. If all values along an axis are NaN, returns NaN for that slice.
Remarks
nansum(NDArray, int?, bool)
Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.
public static NDArray nansum(NDArray a, int? axis = null, bool keepdims = false)
Parameters
aNDArrayArray containing numbers whose sum is desired. If a is not an array, a conversion is attempted.
axisint?Axis or axes along which the sum is computed. The default is to compute the sum of the flattened array.
keepdimsboolIf this is set to True, the axes which are reduced are left in the result as dimensions with size one.
Returns
- NDArray
A new array containing the sum, with NaN values treated as zero.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nansum.html Only applicable to float and double arrays. For integer arrays, this is equivalent to np.sum (no NaN values possible).
nanvar(NDArray, int?, bool, int)
Compute the variance along the specified axis, while ignoring NaNs. Returns the variance of the array elements, a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis.
public static NDArray nanvar(NDArray a, int? axis = null, bool keepdims = false, int ddof = 0)
Parameters
aNDArrayArray containing numbers whose variance is desired.
axisint?Axis or axes along which the variance is computed. The default is to compute the variance of the flattened array.
keepdimsboolIf this is set to True, the axes which are reduced are left in the result as dimensions with size one.
ddofintMeans Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of non-NaN elements. By default ddof is zero.
Returns
- NDArray
A new array containing the variance. If all values along an axis are NaN, returns NaN for that slice.
Remarks
ndarray(Shape, DType, Array, char)
Create an array.
public static NDArray ndarray(Shape shape, DType dtype = null, Array buffer = null, char order = 'F')
Parameters
shapeShapeShape of the array.
dtypeDTypeData type. Default is float32.
bufferArrayOptional buffer to use for data. If null, allocates new memory filled with zeros.
ordercharMemory order. Note: Only C-order is supported, F-order parameter is accepted but ignored.
Returns
- NDArray
New NDArray with the specified shape and dtype.
Remarks
This function creates an NDArray directly without going through TensorEngine. Memory allocation is not backend-specific - all backends use the same unmanaged memory.
ndenumerate(NDArray)
Multidimensional index iterator — returns an iterator yielding pairs of array coordinates and values.
public static np.NDEnumerate ndenumerate(NDArray arr)
Parameters
arrNDArrayInput array. Anything implicitly convertible to NDArray works (
new[,] {{1, 2}, {3, 4}}, a scalar, …), matching NumPy'snp.asarray(arr)coercion of array_like input.
Returns
Remarks
ndenumerate<T>(NDArray)
Typed form of ndenumerate(NDArray) — yields T
instead of a boxed object. NumSharp extension (NumPy has no typed variant,
because Python has no unboxed generics); prefer it in hot loops, where the boxing
of the untyped form dominates the walk.
public static np.NDEnumerate<T> ndenumerate<T>(NDArray arr) where T : unmanaged
Parameters
arrNDArray
Returns
- np.NDEnumerate<T>
Type Parameters
TMust be the array's element type — no conversion is performed.
ndindex(int[])
int[] overload — long[] is the house shape type, but an existing
int[] does not convert to it by array covariance, so it gets its own entry.
Deliberately NOT params: individual int arguments already widen into
the params long[] form, and a second params overload would make the
zero-argument call np.ndindex() ambiguous.
public static np.NDIndex ndindex(int[] shape)
Parameters
shapeint[]
Returns
ndindex(params long[])
An N-dimensional iterator object to index arrays.
Given the shape of an array, an np.NDIndex instance iterates over the N-dimensional index of the array. At each iteration an index array is returned; the last dimension is iterated over first.
public static np.NDIndex ndindex(params long[] shape)
Parameters
shapelong[]The size of each dimension, passed as individual parameters (
np.ndindex(3, 2, 1)) or as a single array (np.ndindex(arr.shape)). Both spellings bind to this oneparamsoverload, so NumPy's "ints, or a single tuple of ints" rule holds for free.
Returns
Remarks
nditer(NDArray, string[], string[], DType[], char, string, int[][], long[], long)
Efficient multi-dimensional iterator object to iterate over arrays.
public static np.NDIterator nditer(NDArray op, string[] flags = null, string[] op_flags = null, DType[] op_dtypes = null, char order = 'K', string casting = "safe", int[][] op_axes = null, long[] itershape = null, long buffersize = 0)
Parameters
opNDArrayThe array to iterate over.
flagsstring[]Flags controlling iterator behaviour:
buffered,c_index,f_index,multi_index,common_dtype,copy_if_overlap,delay_bufalloc,external_loop,grow_inner(a.k.a.growinner),ranged,refs_ok,reduce_ok,zerosize_ok.op_flagsstring[]Per-operand flags:
readonly(default),readwrite,writeonly,allocate,no_broadcast,contig,aligned,nbo,copy,updateifcopy,no_subtype,arraymask,writemasked,overlap_assume_elementwise,virtual.op_dtypesDType[]The required data type(s) of the operands.
ordercharIteration order:
'C','F','A'or'K'(default).castingstringCasting rule when making a copy or buffering:
"no","equiv","safe"(default),"same_kind","unsafe".op_axesint[][]Per-operand list of axes, mapping iterator dimensions to operand dimensions (-1 = newaxis).
itershapelong[]The desired shape of the iterator.
buffersizelongBuffer size to use when buffering is enabled; 0 selects the default.
Returns
Remarks
nditer(NDArray[], string[], string[][], DType[], char, string, int[][], long[], long)
Multi-operand form — NumPy's np.nditer([a, b, …]). A null entry in
op is an output slot to be ALLOCATED by the iterator (NumPy's
None), which then defaults to writeonly, allocate.
public static np.NDIterator nditer(NDArray[] op, string[] flags = null, string[][] op_flags = null, DType[] op_dtypes = null, char order = 'K', string casting = "safe", int[][] op_axes = null, long[] itershape = null, long buffersize = 0)
Parameters
opNDArray[]The array to iterate over.
flagsstring[]Flags controlling iterator behaviour:
buffered,c_index,f_index,multi_index,common_dtype,copy_if_overlap,delay_bufalloc,external_loop,grow_inner(a.k.a.growinner),ranged,refs_ok,reduce_ok,zerosize_ok.op_flagsstring[][]One flag list per operand. A SINGLE inner list is broadcast to every operand — NumPy's "flat list of strings applies to all operands" convenience.
op_dtypesDType[]The required data type(s) of the operands.
ordercharIteration order:
'C','F','A'or'K'(default).castingstringCasting rule when making a copy or buffering:
"no","equiv","safe"(default),"same_kind","unsafe".op_axesint[][]Per-operand list of axes, mapping iterator dimensions to operand dimensions (-1 = newaxis).
itershapelong[]The desired shape of the iterator.
buffersizelongBuffer size to use when buffering is enabled; 0 selects the default.
Returns
Remarks
nditer_chunks<T>(NDArray, bool, char)
Typed CHUNK iteration — hands out a Span<T> per inner loop rather than
one element at a time, so the body can be vectorized or passed to
TensorPrimitives. The typed analogue of NumPy's external_loop, except
that a Span<T> is directly consumable by .NET's vector APIs where
NumPy's chunk is another ndarray.
foreach (Span<double> chunk in np.nditer_chunks<double>(a, writeable: true))
TensorPrimitives.Multiply(chunk, 2.0, chunk);
A C-contiguous array arrives as a SINGLE chunk covering the whole array — and so do F-contiguous, transposed and reversed views, which the iterator coalesces.
public static np.NDChunkIter<T> nditer_chunks<T>(NDArray op, bool writeable = false, char order = 'K') where T : unmanaged
Parameters
opNDArrayThe array to iterate over.
writeableboolOpen the operand
readwriteso assignments through therefreach the array. Broadcast views are read-only and are rejected, with NumPy's message.ordercharIteration order:
'K'(default, memory order — matches NumPy'snp.nditer),'C','F'or'A'. See np.NDRefIter<T> for why the default is NOT logical C-order.
Returns
- np.NDChunkIter<T>
Type Parameters
TMust be EXACTLY the array's element type — no conversion or casting is performed, because a
refcannot convert. A mismatch throws rather than reinterpreting the bytes.
Remarks
NumSharp extension: NumPy has no typed iteration, because Python has no unboxed
generics. The traversal is NumSharp's NDIterRef — the same engine
np.nditer drives — so every memory layout behaves identically; all that is
gone is the per-element NDArray view, which is what made the boxed
form slow.
Empty arrays iterate zero times, where the boxed np.nditer raises
"Iteration of zero-sized operands is not enabled" unless given NumPy's
zerosize_ok flag. Deliberate: throwing would force every caller to guard a
foreach with if (a.size > 0), which is not how C# collections
behave, and this is an extension rather than a parity surface.
nditer<T>(NDArray, bool, char)
Typed, allocation-free element iteration — the unboxed counterpart of
nditer(NDArray, string[], string[], NPTypeCode[], char, string, int[][], long[], long).
Yields ref T straight into the operand's memory, so reading costs a
dereference and writing goes through to the array.
// read
foreach (ref double x in np.nditer<double>(a))
total += x;
// write in place
foreach (ref double x in np.nditer<double>(a, writeable: true))
x *= 2;
public static np.NDRefIter<T> nditer<T>(NDArray op, bool writeable = false, char order = 'K') where T : unmanaged
Parameters
opNDArrayThe array to iterate over.
writeableboolOpen the operand
readwriteso assignments through therefreach the array. Broadcast views are read-only and are rejected, with NumPy's message.ordercharIteration order:
'K'(default, memory order — matches NumPy'snp.nditer),'C','F'or'A'. See np.NDRefIter<T> for why the default is NOT logical C-order.
Returns
Type Parameters
TMust be EXACTLY the array's element type — no conversion or casting is performed, because a
refcannot convert. A mismatch throws rather than reinterpreting the bytes.
Remarks
NumSharp extension: NumPy has no typed iteration, because Python has no unboxed
generics. The traversal is NumSharp's NDIterRef — the same engine
np.nditer drives — so every memory layout behaves identically; all that is
gone is the per-element NDArray view, which is what made the boxed
form slow.
Empty arrays iterate zero times, where the boxed np.nditer raises
"Iteration of zero-sized operands is not enabled" unless given NumPy's
zerosize_ok flag. Deliberate: throwing would force every caller to guard a
foreach with if (a.size > 0), which is not how C# collections
behave, and this is an extension rather than a parity surface.
negative(NDArray, NDArray, NDArray, DType)
Numerical negative, element-wise.
Mirrors NumPy's ufunc signature: negative(x, /, out=None, *, where=True, dtype=None).
public static NDArray negative(NDArray nd, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
ndNDArrayoutNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): selects the loop, so negative(bool, dtype: float64) is legal while plain negative(bool) raises (NumPy parity).
Returns
Remarks
nested_iters(NDArray, int[][], string[], string[][], DType[], char, string, long)
Create nditers for use in nested loops (NumPy's np.nested_iters). Returns one
np.NDIterator per entry in axes, outermost first, all
iterating the SAME operand buffer over different axis subsets. Advancing an outer
iterator re-bases every inner iterator to its new position — so a
foreach (var _ in i) foreach (var _ in j) ... walks the array in nested loops.
public static np.NDIterator[] nested_iters(NDArray op, int[][] axes, string[] flags = null, string[][] op_flags = null, DType[] op_dtypes = null, char order = 'K', string casting = "safe", long buffersize = 0)
Parameters
opNDArrayThe array to iterate over.
axesint[][]One integer list per nesting level; each is used as the
op_axesfor that level's iterator. Must have at least 2 entries, and no axis may appear in more than one entry.flagsstring[]Global iterator flags (see nditer(NDArray, string[], string[], DType[], char, string, int[][], long[], long)).
op_flagsstring[][]Per-operand flags.
op_dtypesDType[]Per-operand iteration dtypes.
ordercharIteration order ('C'/'F'/'A'/'K').
castingstringCasting rule.
buffersizelongBuffer size (applied to the innermost level only, as in NumPy).
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nested_iters.html
Parity: the multi_index path — the documented primary use — is bit-exact with NumPy
2.4.2 across single/multiple operands, any axis order, and any nesting depth (coordinates
AND values pair identically). One KNOWN divergence: WITHOUT multi_index, the pure
value-stream TRAVERSAL ORDER can differ, because NumSharp's underlying np.NDIterator
currently reorders op_axes iteration by memory (F-like) regardless of the order
argument, where NumPy follows order (C/F/K). This is a pre-existing NDIter op_axes
limitation, not a property of the nesting itself; track multi_index for order parity.
nested_iters(NDArray[], int[][], string[], string[][], DType[], char, string, long)
Create nditers for use in nested loops (NumPy's np.nested_iters). Returns one
np.NDIterator per entry in axes, outermost first, all
iterating the SAME operand buffer over different axis subsets. Advancing an outer
iterator re-bases every inner iterator to its new position — so a
foreach (var _ in i) foreach (var _ in j) ... walks the array in nested loops.
public static np.NDIterator[] nested_iters(NDArray[] op, int[][] axes, string[] flags = null, string[][] op_flags = null, DType[] op_dtypes = null, char order = 'K', string casting = "safe", long buffersize = 0)
Parameters
opNDArray[]The array to iterate over.
axesint[][]One integer list per nesting level; each is used as the
op_axesfor that level's iterator. Must have at least 2 entries, and no axis may appear in more than one entry.flagsstring[]Global iterator flags (see nditer(NDArray, string[], string[], DType[], char, string, int[][], long[], long)).
op_flagsstring[][]Per-operand flags.
op_dtypesDType[]Per-operand iteration dtypes.
ordercharIteration order ('C'/'F'/'A'/'K').
castingstringCasting rule.
buffersizelongBuffer size (applied to the innermost level only, as in NumPy).
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.nested_iters.html
Parity: the multi_index path — the documented primary use — is bit-exact with NumPy
2.4.2 across single/multiple operands, any axis order, and any nesting depth (coordinates
AND values pair identically). One KNOWN divergence: WITHOUT multi_index, the pure
value-stream TRAVERSAL ORDER can differ, because NumSharp's underlying np.NDIterator
currently reorders op_axes iteration by memory (F-like) regardless of the order
argument, where NumPy follows order (C/F/K). This is a pre-existing NDIter op_axes
limitation, not a property of the nesting itself; track multi_index for order parity.
nextafter(NDArray, NDArray, NDArray, NDArray, DType)
Return the next floating-point value after x1 towards x2, element-wise.
Mirrors NumPy's ufunc signature: nextafter(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray nextafter(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayValues to find the next representable value of.
x2NDArrayThe direction where to look for the next representable value of x1. If shapes differ they must broadcast to a common shape.
outNDArrayA location into which the result is stored (NumPy ufunc out=).
whereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (float-family only).
Returns
- NDArray
The next representable values of x1 in the direction of x2. This is a scalar if both x1 and x2 are scalars.
Remarks
nonzero(NDArray)
Return the indices of the elements that are non-zero. Returns a tuple of arrays, one for each dimension of a, containing the indices of the non-zero elements in that dimension.The values in a are always tested and returned in row-major, C-style order. To group the indices by element, rather than dimension, use argwhere, which returns a row for each non-zero element.
public static NDArray<long>[] nonzero(NDArray a)
Parameters
aNDArrayInput array.
Returns
Remarks
not_equal(NDArray, NDArray, NDArray, NDArray, DType)
Return (x1 != x2) element-wise.
Mirrors NumPy's ufunc signature: not_equal(x1, x2, /, out=None, *, where=True, dtype=None).
A plain call returns a bool-dtype array (the instance is an NDArray<TDType> of bool —
cast or use the != operator for the typed wrapper).
public static NDArray not_equal(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayInput array.
x2NDArrayInput array.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written; masked-off out slots keep prior contents.
dtypeDTypeValidate-only (NumPy parity): comparisons have bool loops only — any non-bool request raises the no-loop TypeError.
Returns
Remarks
not_equal(NDArray, object)
Return (x1 != x2) element-wise with scalar.
public static NDArray<bool> not_equal(NDArray x1, object x2)
Parameters
Returns
not_equal(object, NDArray)
Return (x1 != x2) element-wise with scalar on left.
public static NDArray<bool> not_equal(object x1, NDArray x2)
Parameters
Returns
ones(Shape)
Return a new array of given shape and type, filled with ones.
public static NDArray ones(Shape shape)
Parameters
shapeShapeShape of the new array.
Returns
Remarks
ones(Shape, DType, string)
Return a new array of given shape and type, filled with ones.
public static NDArray ones(Shape shape, DType dtype, string device = null)
Parameters
shapeShapeShape of the new array.
dtypeDTypeThe desired dtype for the array — one descriptor parameter, like NumPy's
dtype: a C# Type, an NPTypeCode, a NumPy dtype string ("f4") or a DType (uint8) all convert implicitly. Default (null) is float64 / double.devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity).
Returns
Remarks
ones(Shape, char, DType)
Return a new array of ones with a specified memory layout — the port of NumPy's
np.ones(shape, dtype, order='C') order parameter (mirrors empty(Shape, char, DType)).
public static NDArray ones(Shape shape, char order, DType dtype = null)
Parameters
shapeShapeShape of the new array.
ordercharMemory layout: 'C' (row-major), 'F' (column-major), 'A'/'K' (default to 'C' with no source).
dtypeDTypeDesired dtype (a Type, NPTypeCode, dtype string or DType — all convert implicitly). Default is float64 / double.
Returns
- NDArray
Array of ones in the requested layout (the fill is order-independent, so only the flags differ).
Remarks
ones(int)
Return a new array of given shape and type, filled with ones.
public static NDArray ones(int shape)
Parameters
shapeint
Returns
Remarks
ones(int[])
Return a new array of given shape and type, filled with ones.
public static NDArray ones(int[] shape)
Parameters
shapeint[]Shape of the new array.
Returns
Remarks
ones(int[], DType)
Return a new array of given shape and type, filled with ones.
public static NDArray ones(int[] shape, DType dtype)
Parameters
shapeint[]Shape of the new array.
dtypeDTypeThe desired data-type for the array, e.g., uint8. Default is float64 / double.
Returns
Remarks
ones(long[])
Return a new array of given shape and type, filled with ones.
public static NDArray ones(long[] shape)
Parameters
shapelong[]Shape of the new array.
Returns
Remarks
ones_like(NDArray, DType, char, string)
Return an array of ones with the same shape and type as a given array.
public static NDArray ones_like(NDArray a, DType dtype, char order, string device = null)
Parameters
aNDArrayArray of ones with the same shape and type as a.
dtypeDTypeOverrides the data type of the result.
ordercharMemory layout: 'C', 'F', 'A' or 'K' (default, preserves source layout).
devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity).
Returns
- NDArray
Array of ones with the same shape and type as
nd.
Remarks
ones_like(NDArray, DType, string)
Return an array of ones with the same shape and type as a given array.
public static NDArray ones_like(NDArray a, DType dtype = null, string device = null)
Parameters
aNDArrayArray of ones with the same shape and type as a.
dtypeDTypeOverrides the data type of the result.
devicestring
Returns
- NDArray
Array of zeros with the same shape and type as
nd.
Remarks
ones<T>(int[])
Return a new array of given shape and type, filled with ones.
public static NDArray ones<T>(int[] shape) where T : unmanaged
Parameters
shapeint[]Shape of the new array.
Returns
Type Parameters
Remarks
outer(NDArray, NDArray, NDArray)
Compute the outer product of two vectors. Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product[R60] is:
public static NDArray outer(NDArray a, NDArray b, NDArray @out = null)
Parameters
aNDArrayFirst input vector. Input is flattened if not already 1-dimensional.
bNDArraySecond input vector. Input is flattened if not already 1-dimensional.
outNDArrayA location into which the result is stored. Its shape must be
(a.size, b.size). Returned as-is when given. NumPy computesouteras a singlemultiply, sooutfollows the ufunc rules exactly — it joins the broadcast (a shape mismatch is the ufunc broadcast error) and accepts a same_kind cast from the product dtype.
Returns
- NDArray
out[i, j] = a[i] * b[j]
Remarks
pad(NDArray, IDictionary<int, object>, PadFunc, object)
public static NDArray pad(NDArray array, IDictionary<int, object> pad_width, np.PadFunc mode, object kwargs = null)
Parameters
Returns
pad(NDArray, IDictionary<int, object>, string, object, object, object, string)
public static NDArray pad(NDArray array, IDictionary<int, object> pad_width, string mode = "constant", object constant_values = null, object end_values = null, object stat_length = null, string reflect_type = "even")
Parameters
arrayNDArraypad_widthIDictionary<int, object>modestringconstant_valuesobjectend_valuesobjectstat_lengthobjectreflect_typestring
Returns
pad(NDArray, int, PadFunc, object)
public static NDArray pad(NDArray array, int pad_width, np.PadFunc mode, object kwargs = null)
Parameters
Returns
pad(NDArray, int, string, object, object, object, string)
Pad an array. Scalar pad_width applies (pad_width, pad_width)
to every axis.
public static NDArray pad(NDArray array, int pad_width, string mode = "constant", object constant_values = null, object end_values = null, object stat_length = null, string reflect_type = "even")
Parameters
arrayNDArraypad_widthintmodestringconstant_valuesobjectend_valuesobjectstat_lengthobjectreflect_typestring
Returns
Remarks
pad(NDArray, int[,], PadFunc, object)
public static NDArray pad(NDArray array, int[,] pad_width, np.PadFunc mode, object kwargs = null)
Parameters
Returns
pad(NDArray, int[,], string, object, object, object, string)
public static NDArray pad(NDArray array, int[,] pad_width, string mode = "constant", object constant_values = null, object end_values = null, object stat_length = null, string reflect_type = "even")
Parameters
arrayNDArraypad_widthint[,]modestringconstant_valuesobjectend_valuesobjectstat_lengthobjectreflect_typestring
Returns
pad(NDArray, int[], PadFunc, object)
public static NDArray pad(NDArray array, int[] pad_width, np.PadFunc mode, object kwargs = null)
Parameters
Returns
pad(NDArray, int[], string, object, object, object, string)
public static NDArray pad(NDArray array, int[] pad_width, string mode = "constant", object constant_values = null, object end_values = null, object stat_length = null, string reflect_type = "even")
Parameters
arrayNDArraypad_widthint[]modestringconstant_valuesobjectend_valuesobjectstat_lengthobjectreflect_typestring
Returns
pad(NDArray, (int before, int after), PadFunc, object)
public static NDArray pad(NDArray array, (int before, int after) pad_width, np.PadFunc mode, object kwargs = null)
Parameters
Returns
pad(NDArray, (int before, int after), string, object, object, object, string)
public static NDArray pad(NDArray array, (int before, int after) pad_width, string mode = "constant", object constant_values = null, object end_values = null, object stat_length = null, string reflect_type = "even")
Parameters
arrayNDArraypad_width(int AxisA, int AxisB)modestringconstant_valuesobjectend_valuesobjectstat_lengthobjectreflect_typestring
Returns
partition(NDArray, NDArray, int?, string, string)
Return a partitioned copy with the kth indices given as an ARRAY — NumPy's array-kth form, which is what makes its kth-dtype rejections reachable: a bool kth raises "Booleans unacceptable as partition index", a non-integer kth "Partition index must be integer" (TypeError), a >1-D kth "object too deep for desired array" (checked BEFORE the axis, like NumPy). Integer kth values cast to intp with NumPy's modular wrap (uint64 past 2^63 goes negative; 2^64-1 is a legal -1). 0-d and any layout accepted.
public static NDArray partition(NDArray a, NDArray kth, int? axis = -1, string kind = "introselect", string order = null)
Parameters
Returns
Remarks
partition(NDArray, int, int?, string, string)
Return a partitioned copy of an array: the element at index kth
lands in its final sorted position, everything smaller lies before it and everything
equal or greater behind it — the order WITHIN the two sides is undefined
(NumPy np.partition).
public static NDArray partition(NDArray a, int kth, int? axis = -1, string kind = "introselect", string order = null)
Parameters
aNDArrayArray to be partitioned.
kthintElement index to partition by; negative wraps from the end.
axisint?Axis to partition along. -1 (default) = last axis; null flattens first.
kindstringSelection algorithm — only 'introselect' exists, exactly like NumPy; anything else raises NumPy's verbatim ValueError.
orderstringStructured-dtype field order — NumSharp has no structured dtypes, so any non-null value raises NumPy's "Cannot specify order when the array has no fields."
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.partition.html
Validation follows NumPy's probed order: kind → order → axis → kth ("kth(=N) out of
bounds (M)" reports the post-wrap value; an EMPTY array skips the kth bounds check).
NaN floats partition to the end (original bit patterns preserved); complex uses NumPy's
lexicographic real-then-imag ordering. The result is a fresh C-contiguous copy (house
np.sort convention — NumPy's copy(order='K') keeps F-order for F-inputs; values identical).
partition(NDArray, int[], int?, string, string)
Return a partitioned copy of an array, partitioning around EVERY index in
kth at once (each lands in its final sorted position; the ranges
between them are mutually ordered). NumPy np.partition with a kth sequence.
public static NDArray partition(NDArray a, int[] kth, int? axis = -1, string kind = "introselect", string order = null)
Parameters
aNDArrayArray to be partitioned.
kthint[]Element indices to partition by; negatives wrap. NumSharp reads an empty array as NumPy's
np.array([], dtype=intp)— a valid no-op returning a plain copy (Python's bare[]is float64 and raises TypeError; a typed int[] is never ambiguous).axisint?Axis to partition along. -1 (default) = last axis; null flattens first.
kindstringSelection algorithm — only 'introselect' exists.
orderstringMust stay null (no structured dtypes).
Returns
Remarks
percentile(NDArray, NDArray, int?, NDArray, bool, string, bool)
public static NDArray percentile(NDArray a, NDArray q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)
Parameters
Returns
percentile(NDArray, double, int[], NDArray, bool, string, bool)
public static NDArray percentile(NDArray a, double q, int[] axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)
Parameters
Returns
percentile(NDArray, double, int?, NDArray, bool, string, bool)
Compute the q-th percentile of the data along the specified axis.
q must be in [0, 100]. Equivalent to np.quantile(a, q/100).
public static NDArray percentile(NDArray a, double q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)
Parameters
Returns
Remarks
percentile(NDArray, double[], int[], NDArray, bool, string, bool)
public static NDArray percentile(NDArray a, double[] q, int[] axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)
Parameters
Returns
percentile(NDArray, double[], int?, NDArray, bool, string, bool)
public static NDArray percentile(NDArray a, double[] q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)
Parameters
Returns
permute_dims(NDArray, int[])
Permute the axes (dimensions) of an array.
Array API standard alias of transpose(NDArray, int[]).
public static NDArray permute_dims(NDArray a, int[] axes = null)
Parameters
aNDArrayInput array.
axesint[]If specified, it must be a permutation of
[0, 1, ..., N-1]whereNis the number of axes ofa. Negative indices can also be used. The i-th axis of the returned array will correspond to the axis numberedaxes[i]of the input. If not specified, defaults to reversing the order of the axes.
Returns
- NDArray
awith its axes permuted. A view is returned whenever possible.
Remarks
place(NDArray, NDArray, NDArray)
Change elements of arr based on a boolean mask.
Where mask is true (walked in C-order), the
next value from vals (cycling) is written into
arr. In-place.
public static void place(NDArray arr, NDArray mask, NDArray vals)
Parameters
arrNDArrayTarget array (modified in place).
maskNDArrayBoolean mask. Must have the same total size as
arr— NumPy allows shape mismatch as long as element counts match.valsNDArrayValues to write. Cast to
arr's dtype and cycled to fill the True positions. Must be non-empty when at least one mask entry is True (NumPy parity).
Remarks
poly(NDArray)
Find the coefficients of a polynomial with the given sequence of roots (leading coefficient 1). A square 2-D array is treated as a matrix, returning the coefficients of its characteristic polynomial (via eigvals(NDArray)).
public static NDArray poly(NDArray seq_of_zeros)
Parameters
seq_of_zerosNDArrayA 1-D sequence of roots, or a square 2-D array.
Returns
- NDArray
1-D coefficients highest degree first,
c[0] == 1.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.poly.html
An empty input returns the 0-d scalar 1.0 (NumPy's Python float 1.0).
polyadd(NDArray, NDArray)
Find the sum of two polynomials. The shorter input is zero-extended on the high-degree side.
public static NDArray polyadd(NDArray a1, NDArray a2)
Parameters
Returns
Remarks
polyder(NDArray, int)
Return the derivative of the specified order of a polynomial.
public static NDArray polyder(NDArray p, int m = 1)
Parameters
pNDArrayPolynomial coefficients, highest degree first.
mintOrder of differentiation (default 1).
Returns
- NDArray
A new polynomial representing the derivative.
Remarks
polydiv(NDArray, NDArray)
Returns the quotient and remainder of polynomial division u / v.
public static (NDArray q, NDArray r) polydiv(NDArray u, NDArray v)
Parameters
Returns
- (NDArray Lhs, NDArray Rhs)
(q, r)— quotient and remainder coefficients, floating (or complex) dtype.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.polydiv.html
A poly1d input does NOT force a poly1d return here (a C# tuple slot is a fixed
type); the poly1d / operator performs that wrapping instead.
polyfit(NDArray, NDArray, int, double?, bool, NDArray, object)
Least squares polynomial fit — fit a polynomial p[0]*x**deg + ... + p[deg] of degree
deg to points (x, y), minimising the squared error.
public static PolyfitResult polyfit(NDArray x, NDArray y, int deg, double? rcond = null, bool full = false, NDArray w = null, object cov = null)
Parameters
xNDArrayx-coordinates, shape
(M,).yNDArrayy-coordinates, shape
(M,)or(M, K)(one dataset per column).degintDegree of the fitting polynomial.
rconddouble?Relative condition number; default
len(x) * eps.fullboolWhen true, the returned PolyfitResult also carries the SVD diagnostics.
wNDArrayOptional weights, shape
(M,).covobjectnull/false(default),true, or the string"unscaled"— when truthy the result also carries the covariance matrix (only meaningful whenfullis false).
Returns
- PolyfitResult
A PolyfitResult that converts implicitly to the coefficient array; deconstruct it for the
fullfive-tuple or thecovtwo-tuple.
Remarks
polyint(NDArray, int, NDArray)
Return an antiderivative (indefinite integral) of a polynomial.
public static NDArray polyint(NDArray p, int m = 1, NDArray k = null)
Parameters
pNDArrayPolynomial to integrate (coefficients, highest degree first).
mintOrder of the antiderivative (default 1).
kNDArrayIntegration constants, highest-order term first.
null(default) means all zero. Form == 1a single scalar may be given.
Returns
- NDArray
The antiderivative — always floating (or complex) because of the term-wise division.
Remarks
polyint(NDArray, int, double)
Convenience overload — polyint with a single scalar integration constant.
public static NDArray polyint(NDArray p, int m, double k)
Parameters
Returns
polymul(NDArray, NDArray)
Find the product of two polynomials — the (full-mode) convolution of their coefficients.
Leading zeros of each input are dropped first (NumPy wraps each in poly1d).
public static NDArray polymul(NDArray a1, NDArray a2)
Parameters
Returns
Remarks
polysub(NDArray, NDArray)
Difference (subtraction) of two polynomials, a1 - a2.
public static NDArray polysub(NDArray a1, NDArray a2)
Parameters
Returns
Remarks
polyval(NDArray, NDArray)
Evaluate a polynomial at specific values.
If p has length N the value returned is
p[0]x*(N-1) + p[1]x*(N-2) + ... + p[N-2]*x + p[N-1], computed with Horner's scheme.
public static NDArray polyval(NDArray p, NDArray x)
Parameters
pNDArray1-D array of polynomial coefficients, highest degree first.
xNDArrayA number, or an array of numbers, at which to evaluate
p.
Returns
- NDArray
The evaluated values, of dtype
result_type(p, x)and the shape ofx.
Remarks
polyval(poly1d, poly1d)
Evaluate a polynomial p at another polynomial (composition).
public static poly1d polyval(poly1d p, poly1d x)
Parameters
Returns
Remarks
positive(NDArray, NDArray, NDArray, DType)
Numerical positive, element-wise (identity: returns +x, a copy).
Mirrors NumPy's ufunc signature: positive(x, /, out=None, *, where=True, dtype=None).
public static NDArray positive(NDArray nd, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
ndNDArrayoutNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): positive(i32, dtype: float64) widens; bool loop requests raise NumPy's did-not-contain-a-loop TypeError (positive has no bool loop, but positive(bool, dtype: float64) is legal).
Returns
Remarks
power(NDArray, NDArray)
First array elements raised to powers from second array, element-wise. Supports broadcasting between x1 and x2.
public static NDArray power(NDArray x1, NDArray x2)
Parameters
Returns
- NDArray
The bases in x1 raised to the exponents in x2.
Remarks
power(NDArray, NDArray, NDArray, NDArray, DType)
First array elements raised to powers from second array, element-wise.
Mirrors NumPy's ufunc signature: power(x1, x2, /, out=None, *, where=True, dtype=None).
public static NDArray power(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
x1NDArrayThe bases.
x2NDArrayThe exponents (array).
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs in this dtype (power(2, -1, dtype: float64) = 0.5; inputs must be same_kind-castable to it).
Returns
Remarks
power(NDArray, object)
First array elements raised to powers from second array, element-wise.
public static NDArray power(NDArray x1, object x2)
Parameters
Returns
- NDArray
The bases in x1 raised to the exponents in x2. This is a scalar NDArray if both x1 and x2 are scalars.
Remarks
power(in NDArray, in NDArray)
First array elements raised to powers from second array, element-wise. Supports broadcasting between x1 and x2.
public static NDArray power(in NDArray x1, in NDArray x2)
Parameters
Returns
- NDArray
The bases in x1 raised to the exponents in x2.
Remarks
printoptions(int?, int?, int?, int?, bool?, string, string, char?, string)
Context manager for setting print options (NumPy's np.printoptions). Restores the
previous options when disposed.
public static IDisposable printoptions(int? precision = null, int? threshold = null, int? edgeitems = null, int? linewidth = null, bool? suppress = null, string nanstr = null, string infstr = null, char? sign = null, string floatmode = null)
Parameters
precisionint?thresholdint?edgeitemsint?linewidthint?suppressbool?nanstrstringinfstrstringsignchar?floatmodestring
Returns
Examples
using (np.printoptions(precision: 2, suppress: true)) { Console.WriteLine(arr); }
Remarks
prod(NDArray, int?, DType, bool)
Return the product of array elements over a given axis.
public static NDArray prod(NDArray a, int? axis = null, DType dtype = null, bool keepdims = false)
Parameters
aNDArrayInput data.
axisint?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.
dtypeDTypeThe 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.
keepdimsboolIf 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
promote_types(DType, DType)
Returns the data type with the smallest size and smallest scalar kind to which
both type1 and type2 can be safely cast — NumPy's np.promote_types(type1, type2)
(PyArray_PromoteTypes, NEP 42): the common DType CLASS of the two operands decides, a
non-parametric class returns its default descriptor and a parametric one (datetime64 / timedelta64)
returns the common_instance — the unit GCD (promote_types('M8[s]', 'm8[ms]') is M8[ms],
promote_types('m8[10s]', 'm8[15s]') is m8[5s]).
public static DType promote_types(DType type1, DType type2)
Parameters
Returns
- DType
The promoted descriptor.
Examples
np.promote_types(DType.Int32, DType.Single) // float64
np.promote_types("M8[s]", "m8[ms]") // datetime64[ms]
np.promote_types("i1", "u1") // int16
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.promote_types.html
Unlike result_type, promote_types only considers types (not values),
and always returns the smallest safe type. A non-native byte order is dropped (promote_types('>i4', '>i4')
is the native int32), exactly as in NumPy.
Exceptions
- DTypePromotionError
No common dtype exists (
promote_types('M8[s]', 'f8')) — NumPy's verbatim text.- TypeError
Incompatible non-linear datetime units (
promote_types('m8[Y]', 'm8[D]')) — verbatim.
promote_types(NPTypeCode, NPTypeCode)
Returns the data type with the smallest size and smallest scalar kind to which both type1 and type2 can be safely cast.
public static DType promote_types(NPTypeCode type1, NPTypeCode type2)
Parameters
type1NPTypeCodeFirst data type.
type2NPTypeCodeSecond data type.
Returns
- DType
The promoted type.
Examples
np.promote_types(NPTypeCode.Int32, NPTypeCode.Single) // Double
np.promote_types(NPTypeCode.Int16, NPTypeCode.UInt16) // Int32
np.promote_types(NPTypeCode.Int8, NPTypeCode.Int8) // Int8
Remarks
The NPTypeCode spelling of promote_types(DType, DType): the same NEP 42 engine, whose answers for the storage-backed types ARE NumSharp's frozen promotion table.
promote_types(Type, Type)
Returns the data type with the smallest size and smallest scalar kind to which both type1 and type2 can be safely cast.
public static DType promote_types(Type type1, Type type2)
Parameters
Returns
- DType
The promoted type as NPTypeCode.
promote_types<T1, T2>()
Returns the data type with the smallest size and smallest scalar kind to which both T1 and T2 can be safely cast.
public static DType promote_types<T1, T2>() where T1 : struct where T2 : struct
Returns
- DType
The promoted type as NPTypeCode.
Type Parameters
T1First type.
T2Second type.
Examples
np.promote_types<int, long>() // Int64
np.promote_types<float, double>() // Double
ptp(NDArray, int[], NDArray, bool)
public static NDArray ptp(NDArray a, int[] axis, NDArray @out = null, bool keepdims = false)
Parameters
Returns
ptp(NDArray, int?, NDArray, bool)
Range of values (maximum - minimum) along an axis.
Equivalent to np.amax(a, axis) - np.amin(a, axis); dtype is preserved,
so unsigned/signed integer overflow wraps the same way NumPy does
(e.g. ptp(uint8[0,255]) == 255, ptp(int8[-128,127]) == -1).
public static NDArray ptp(NDArray a, int? axis = null, NDArray @out = null, bool keepdims = false)
Parameters
Returns
Remarks
put(NDArray, NDArray, NDArray, string)
Replace elements of a with given values, at the
specified flat indices. In-place — modifies a.
Equivalent to a.flat[indices] = values with cyclic
broadcasting of values.
public static void put(NDArray a, NDArray indices, NDArray values, string mode = "raise")
Parameters
aNDArrayTarget array (modified in place).
indicesNDArrayInteger array of flat indices (cast to int64 internally). Indexing is into the C-order flattening of
a.valuesNDArrayValues to write. Cast to
a's dtype. Cycles modulo its size — shorter thanindicesis fine.modestringBoundary mode:
"raise"(default),"wrap", or"clip".
Remarks
put(NDArray, long, object, string)
Scalar-index, scalar-value convenience overload.
public static void put(NDArray a, long index, object value, string mode = "raise")
Parameters
quantile(NDArray, NDArray, int?, NDArray, bool, string, bool)
NDArray-q overload — accepts a 0-D or 1-D NDArray of quantile values. Higher-rank q is rejected (NumPy raises "q must be a scalar or 1d").
public static NDArray quantile(NDArray a, NDArray q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)
Parameters
Returns
quantile(NDArray, double, int[], NDArray, bool, string, bool)
Compute the q-th quantile, reducing along multiple axes.
public static NDArray quantile(NDArray a, double q, int[] axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)
Parameters
Returns
quantile(NDArray, double, int?, NDArray, bool, string, bool)
Compute the q-th quantile of the data along the specified axis.
q must be in the range [0, 1].
public static NDArray quantile(NDArray a, double q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)
Parameters
Returns
Remarks
quantile(NDArray, double[], int[], NDArray, bool, string, bool)
public static NDArray quantile(NDArray a, double[] q, int[] axis, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)
Parameters
Returns
quantile(NDArray, double[], int?, NDArray, bool, string, bool)
Compute the q-th quantiles of the data along the specified axis.
Each value in q must be in [0, 1]. Result's first axis is q.
public static NDArray quantile(NDArray a, double[] q, int? axis = null, NDArray @out = null, bool overwrite_input = false, string method = "linear", bool keepdims = false)
Parameters
Returns
rad2deg(NDArray, NDArray, NDArray, DType)
Convert angles from radians to degrees.
public static NDArray rad2deg(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayAngle in radians.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of.
Returns
- NDArray
The corresponding angle in degrees. This is a scalar if x is a scalar.
Remarks
radians(NDArray, NDArray, NDArray, DType)
Convert angles from degrees to radians. Alias for deg2rad.
public static NDArray radians(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayAngles in degrees.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of.
Returns
- NDArray
The corresponding angle in radians. This is a scalar if x is a scalar.
Remarks
ravel(NDArray)
Return a contiguous flattened array. A 1-D array, containing the elements of the input, is returned
public static NDArray ravel(NDArray a)
Parameters
aNDArrayInput array. The elements in a are read in the order specified by order, and packed as a 1-D array.
Returns
Remarks
ravel(NDArray, char)
Return a contiguous flattened array. A 1-D array, containing the elements of the input, is returned
public static NDArray ravel(NDArray a, char order)
Parameters
aNDArrayInput array.
ordercharThe order in which to read the elements. 'C' - row-major, 'F' - column-major, 'A' - 'F' if a is F-contiguous (and not C-contiguous) else 'C', 'K' - memory order.
Returns
Remarks
ravel_multi_index(NDArray[], int[], string, char)
Converts a tuple of coordinate arrays into an array of flat indices, applying boundary modes per axis. Inverse of unravel_index(NDArray, int[], char).
public static NDArray<long> ravel_multi_index(NDArray[] multi_index, int[] dims, string mode = "raise", char order = 'C')
Parameters
multi_indexNDArray[]Tuple of integer arrays, one per dimension. All arrays must share the same shape, which becomes the shape of the result.
dimsint[]Shape of the array the indices are unravelling into.
modestringBoundary mode:
"raise"(default — throw on OOB),"wrap"(modulo with sign correction), or"clip"(saturate). Applied to every axis.orderchar'C'(row-major, default) or'F'(column-major). Selects the stride ordering used to fold coordinates into a flat index.
Returns
- NDArray<long>
1-D (or shape-preserving) NDArray<TDType> of long.
Remarks
ravel_multi_index(NDArray[], int[], string[], char)
Per-axis mode overload. modes length must match
dims length.
public static NDArray<long> ravel_multi_index(NDArray[] multi_index, int[] dims, string[] modes, char order = 'C')
Parameters
Returns
ravel_multi_index(long[], int[], string, char)
Scalar convenience overload — folds a single coordinate tuple into a flat index. Equivalent to wrapping each coord in a 0-d NDArray but returns a long directly.
public static long ravel_multi_index(long[] coords, int[] dims, string mode = "raise", char order = 'C')
Parameters
Returns
real(NDArray)
Return the real part of the complex argument, element-wise.
One of the four basic complex-number accessors (with imag(NDArray), angle(NDArray, bool)
and conjugate(NDArray, NDArray, NDArray, DType)) — the standard post-FFT spectrum component extractors: for
A = np.fft.fft(a), A.real / np.real(A) is the real component.
public static NDArray real(NDArray val)
Parameters
valNDArrayInput array.
Returns
- NDArray
For a COMPLEX input: a float64 VIEW onto the real lane — it SHARES memory with
valand is writeable, sonp.real(z)[i] = xwrites through toz[i]'s real part (reproducing NumPy'sz.real; complex128 -> float64). For a REAL / integer / boolean input: NumPy returns the array itself (the real part of a real number is the number), so the input is returned unchanged with its dtype preserved.
Remarks
reciprocal(NDArray, NDArray, NDArray, DType)
Return the reciprocal of the argument, element-wise. Calculates 1/x.
public static NDArray reciprocal(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of.
Returns
- NDArray
Return array containing 1/x for each element in x. This is a scalar if x is a scalar.
Remarks
repeat(NDArray, NDArray, int?)
Repeat elements of an array with per-element repeat counts. Mirrors NumPy
np.repeat(a, repeats, axis): scalar / size-1 repeats broadcasts to
every element along the (flattened or selected) axis; otherwise the length must match.
public static NDArray repeat(NDArray a, NDArray repeats, int? axis = null)
Parameters
aNDArrayInput array.
repeatsNDArrayRepeat counts. Either a 0-d/size-1 array (broadcast) or a 1-D array of length equal to
a.size(axis=None) ora.shape[axis].axisint?Axis along which to repeat.
nullflattens the input.
Returns
- NDArray
A new array with elements repeated according to
repeats.
Remarks
repeat(NDArray, int, int?)
Repeat each element of an array after themselves.
public static NDArray repeat(NDArray a, int repeats, int? axis = null)
Parameters
aNDArrayInput array.
repeatsintThe number of repetitions for each element.
axisint?Axis along which to repeat values.
null(NumPyNone) flattens the input and returns a flat array.
Returns
- NDArray
Output array which has the same shape as
a, except alongaxis.
Remarks
repeat(NDArray, long, int?)
Repeat each element of an array after themselves.
public static NDArray repeat(NDArray a, long repeats, int? axis = null)
Parameters
aNDArrayInput array.
repeatslongThe number of repetitions for each element.
axisint?Axis along which to repeat values.
null(NumPyNone) flattens the input.
Returns
- NDArray
Output array.
Remarks
repeat<T>(T, int)
Repeat a scalar value.
public static NDArray repeat<T>(T a, int repeats) where T : unmanaged
Parameters
aTInput scalar.
repeatsintThe number of repetitions.
Returns
- NDArray
A 1-D array with the scalar repeated.
Type Parameters
T
Remarks
repeat<T>(T, long)
Repeat a scalar value.
public static NDArray repeat<T>(T a, long repeats) where T : unmanaged
Parameters
aTInput scalar.
repeatslongThe number of repetitions.
Returns
- NDArray
A 1-D array with the scalar repeated.
Type Parameters
T
Remarks
require(NDArray, DType, string)
Single-string requirements overload. Mirrors NumPy's iteration semantics exactly: a string
is iterated CHARACTER BY CHARACTER, so "F" is the Fortran flag, "CF" requests
both C and F (and raises), and a multi-character alias such as "F_CONTIGUOUS" is NOT
one token — its '_' is unrecognized and raises. Pass a single-element array
(new[]{ "F_CONTIGUOUS" }) to use the full alias.
public static NDArray require(NDArray a, DType dtype, string requirements)
Parameters
Returns
Remarks
require(NDArray, DType, string[], NDArray)
Return an ndarray of the provided type that satisfies requirements.
public static NDArray require(NDArray a, DType dtype = null, string[] requirements = null, NDArray like = null)
Parameters
aNDArrayThe object to be converted to a type-and-requirement-satisfying array.
dtypeDTypeThe required data-type.
nullpreserves the current dtype.requirementsstring[]The requirements list. Each element is one of (case-insensitive, with aliases):
- 'F_CONTIGUOUS' / 'F' / 'FORTRAN' — ensure a Fortran-contiguous array
- 'C_CONTIGUOUS' / 'C' / 'CONTIGUOUS' — ensure a C-contiguous array
- 'ALIGNED' / 'A' — ensure a data-type aligned array
- 'WRITEABLE' / 'W' — ensure a writable array
- 'OWNDATA' / 'O' — ensure an array that owns its own data
- 'ENSUREARRAY' / 'E' — ensure a base array instead of a subclass (no-op in NumSharp: no ndarray subclasses)
likeNDArrayReference array for NumPy's array-function dispatch — accepted for signature parity but has no observable effect in NumSharp (no array-subclass dispatch).
Returns
- NDArray
Array with the specified requirements and dtype if given. A copy is made only when needed.
Remarks
Port of NumPy 2.x numpy.require. With no requirements this is exactly
asanyarray(a, dtype). Otherwise it resolves an order ('A' by default, or 'C'/'F' when
requested), routes through asarray(NDArray, DType, char, bool?, NDArray, string),
then makes a single copy (in the resolved order) if any of the remaining ALIGNED / WRITEABLE /
OWNDATA flags is not already satisfied. ALIGNED is always satisfied in NumSharp (managed
allocations), so only WRITEABLE (false for broadcast views) and OWNDATA (false for views)
can force a copy. 'ENSUREARRAY' is accepted and stripped but has no effect — NumSharp has no
ndarray subclasses to demote.
https://numpy.org/doc/stable/reference/generated/numpy.require.html
Exceptions
- ValueError
If both 'C' and 'F' order are requested, or a requirement string is not understood.
reshape(NDArray, Shape)
Gives a new shape to an array without changing its data.
public static NDArray reshape(NDArray nd, Shape shape)
Parameters
ndNDArrayArray to be reshaped.
shapeShapeThe new shape should be compatible with the original shape.
Returns
- NDArray
original
ndreshaped without copying.
Remarks
reshape(NDArray, ref Shape)
Gives a new shape to an array without changing its data.
public static NDArray reshape(NDArray nd, ref Shape shape)
Parameters
ndNDArrayArray to be reshaped.
shapeShapeThe new shape should be compatible with the original shape.
Returns
- NDArray
original
ndreshaped without copying.
Remarks
reshape(NDArray, int[])
Gives a new shape to an array without changing its data.
public static NDArray reshape(NDArray nd, int[] shape)
Parameters
ndNDArrayArray to be reshaped.
shapeint[]The new shape should be compatible with the original shape.
Returns
- NDArray
original
ndreshaped without copying.
Remarks
reshape(NDArray, long[])
Gives a new shape to an array without changing its data.
public static NDArray reshape(NDArray nd, long[] shape)
Parameters
ndNDArrayArray to be reshaped.
shapelong[]The new shape should be compatible with the original shape.
Returns
- NDArray
original
ndreshaped without copying.
Remarks
resize(NDArray, Shape)
Return a new array with the specified shape.
If the new array is larger than the original array, then the new array is filled
with repeated copies of a (iterating over a
in C-order, cycling back from the start). Note that this behavior is different from
resize(params long[]) which fills with zeros instead.
NumPy's np.resize takes new_shape as a single argument (an int or a
sequence) — the multi-argument form np.resize(a, 2, 3) is a NumPy TypeError,
so it is not offered here. Pass the shape as an int, a value tuple, an array, or a
Shape; all resolve through Shape's implicit conversions:
np.resize(a, 6), np.resize(a, (2, 3)), np.resize(a, new[]{2, 3}),
np.resize(a, new Shape(2, 3)).
public static NDArray resize(NDArray a, Shape new_shape)
Parameters
aNDArrayArray to be resized.
new_shapeShapeShape of resized array (int / tuple / array / Shape).
Returns
- NDArray
The new array is formed from the data in the old array, repeated if necessary to fill out the required number of elements. The data are repeated iterating over the array in C-order. Result is C-contiguous; dtype matches
a.
Remarks
Exceptions
- ArgumentNullException
If
ais null.- ArgumentException
If any element of
new_shapeis negative.
result_type(params DType[])
Returns the type that results from applying the NumPy type promotion rules to the given descriptors (all strong).
public static DType result_type(params DType[] dtypes)
Parameters
dtypesDType[]One or more descriptors.
Returns
- DType
The result descriptor.
result_type(NDArray, NDArray)
Returns the type that results from applying the NumPy type promotion rules to the two arrays. Convenience overload to avoid params array allocation.
public static DType result_type(NDArray arr1, NDArray arr2)
Parameters
Returns
- DType
The result type from combining the array dtypes.
result_type(params NDArray[])
Returns the type that results from applying the NumPy type promotion rules to the arguments. Every array — 0-d included — is a full (strong) participant, as in NumPy 2.x.
public static DType result_type(params NDArray[] arrays)
Parameters
arraysNDArray[]One or more NDArray objects.
Returns
- DType
The result type from combining the array dtypes.
result_type(NPTypeCode, NPTypeCode)
Returns the type that results from applying the NumPy type promotion rules to the two type codes. Convenience overload to avoid params array allocation.
public static DType result_type(NPTypeCode type1, NPTypeCode type2)
Parameters
type1NPTypeCodeFirst type code.
type2NPTypeCodeSecond type code.
Returns
- DType
The result type from combining the inputs.
result_type(params NPTypeCode[])
Returns the type that results from applying the NumPy type promotion rules to the arguments.
public static DType result_type(params NPTypeCode[] types)
Parameters
typesNPTypeCode[]One or more NPTypeCode values.
Returns
- DType
The result type from combining the inputs.
result_type(params object[])
Returns the type that results from applying the NumPy type promotion rules
to the arguments — NumPy's np.result_type(*arrays_and_dtypes) (PyArray_ResultType) under
NEP 50.
public static DType result_type(params object[] arrays_and_dtypes)
Parameters
arrays_and_dtypesobject[]Arrays and/or dtype arguments: any mix of NDArray, DType, DTypeMeta (a bare class), NPTypeCode, Type, dtype string, and C# scalars.
Returns
- DType
The result descriptor.
Examples
np.result_type(NPTypeCode.Int32, NPTypeCode.Int64) // int64
np.result_type(a, 5) // a.dtype (weak int)
np.result_type(a, 5.0) // float64 for an integer a
np.result_type("M8[s]", "m8[ms]") // datetime64[ms]
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.result_type.html
NEP 50 in C#. Every NDArray — 0-d included — contributes its dtype fully ("strong"), as do
DType, NPTypeCode, Type, dtype strings, bool, char,
Half and decimal values. A C# integer literal (int, long, …), a float/double
or a Complex is WEAK — the analog of a Python int/float/complex — and only contributes its
category: result_type(int8_array, 300) is int8 (no value-based inspection), result_type(int8_array,
1.5) is float64, result_type(float32_array, 1e300) is float32; a lone literal falls back to
int64 / float64 / complex128.
The reduction over three or more operands is NumPy's order-independent PyArray_PromoteDTypeSequence
(result_type(i1, i1, f8, i1) is float64 in every order). Parametric operands resolve their
common_instance (result_type("M8[s]", "m8[ms]", "m8[us]") is datetime64[us]).
Exceptions
- ValueError
at least one array or dtype is required(no operands).- DTypePromotionError
No common dtype exists — NumPy's verbatim text, listing every operand class.
result_type(params string[])
Returns the type that results from applying the NumPy type promotion rules
to the given dtype strings (np.result_type("i1", "f8")). Exists so that a string argument binds the
dtype grammar rather than NumSharp's string→NDArray (character array) conversion.
public static DType result_type(params string[] dtypes)
Parameters
dtypesstring[]
Returns
result_type(Type, Type)
Returns the type that results from applying the NumPy type promotion rules to the two CLR types. Convenience overload to avoid params array allocation.
public static DType result_type(Type type1, Type type2)
Parameters
Returns
- DType
The result type from combining the inputs.
right_shift(NDArray, NDArray)
Shift the bits of an integer to the right.
public static NDArray right_shift(NDArray x1, NDArray x2)
Parameters
x1NDArrayInput array (integer types only).
x2NDArrayNumber of bits to shift (integer types only).
Returns
- NDArray
Array with bits shifted right.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.right_shift.html
Bits are shifted to the right by removing x2 bits from the right of x1. For unsigned integers, this is logical shift (zeros filled from left). For signed integers, this is arithmetic shift (sign bit extended). This operation is equivalent to floor division by 2**x2.
Example: np.right_shift(20, 2) = 5 # 0b10100 -> 0b101
right_shift(NDArray, object)
Shift the bits of an integer to the right by a scalar or array-like amount.
public static NDArray right_shift(NDArray x1, object x2)
Parameters
x1NDArrayInput array (integer types only).
x2objectNumber of bits to shift (scalar or array-like).
Returns
- NDArray
Array with bits shifted right.
rint(NDArray, NDArray, NDArray, DType)
Round elements of the array to the nearest integer, element-wise (round half to even). The result is a float (rint has no integer loop): integer/bool inputs promote to the float tier (bool/int8/uint8 -> float16, int16/uint16 -> float32, int32/int64/... -> float64), floats and complex are preserved. The real and imaginary parts of complex numbers are rounded separately.
public static NDArray rint(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArrayA location into which the result is stored (same_kind cast from the loop dtype).
whereNDArrayBoolean mask; compute only where true, leaving other
outslots unchanged.dtypeDTypeLoop dtype override (must be a float/complex loop).
Returns
- NDArray
An array of the same shape as x, containing the rounded values. This is a scalar if x is a scalar.
Remarks
roll(NDArray, int, int?)
Roll array elements along a given axis.
Elements that roll beyond the last position are re-introduced at the first.
public static NDArray roll(NDArray a, int shift, int? axis = null)
Parameters
aNDArrayInput array.
shiftintThe number of places by which elements are shifted.
axisint?Axis along which elements are shifted. By default, the array is flattened before shifting, after which the original shape is restored.
Returns
- NDArray
Output array, with the same shape as
a.
Remarks
Matches NumPy's algorithm: empty_like + slice-copy pairs. https://numpy.org/doc/stable/reference/generated/numpy.roll.html
roll(NDArray, long, int?)
Roll array elements along a given axis.
Elements that roll beyond the last position are re-introduced at the first.
public static NDArray roll(NDArray a, long shift, int? axis = null)
Parameters
aNDArrayInput array.
shiftlongThe number of places by which elements are shifted.
axisint?Axis along which elements are shifted. By default, the array is flattened before shifting, after which the original shape is restored.
Returns
- NDArray
Output array, with the same shape as
a.
Remarks
Matches NumPy's algorithm: empty_like + slice-copy pairs. https://numpy.org/doc/stable/reference/generated/numpy.roll.html
rollaxis(NDArray, int, int)
Roll the specified axis backwards, until it lies in a given position.
This function continues to be supported for backward compatibility, but you should prefer moveaxis. The moveaxis function was added in NumPy 1.11.
public static NDArray rollaxis(NDArray a, int axis, int start = 0)
Parameters
aNDArrayInput array.
axisintThe axis to roll backwards. The positions of the other axes do not change relative to one another.
startintThe axis is rolled until it lies before this position. The default, 0, results in a “complete” roll.
Returns
Remarks
roots(NDArray)
Return the roots of a polynomial with coefficients given in p.
If p has length n+1 the polynomial is
p[0]x**n + p[1]x(n-1) + ... + p[n].
public static NDArray roots(NDArray p)
Parameters
pNDArrayRank-1 array of polynomial coefficients.
Returns
- NDArray
The roots — the eigenvalues of the companion matrix.
Remarks
rot90(NDArray, int, int[])
Rotate an array by 90 degrees in the plane specified by axes.
Rotation direction is from the first towards the second axis. This means that
for a 2-D array with the default k and axes
the rotation will be counterclockwise.
public static NDArray rot90(NDArray m, int k = 1, int[] axes = null)
Parameters
mNDArrayArray of two or more dimensions.
kintNumber of times the array is rotated by 90 degrees.
axesint[]The array is rotated in the plane defined by the axes. Axes must be different. Defaults to
(0, 1).
Returns
- NDArray
A rotated view of
m.
Remarks
Port of NumPy's numpy.rot90 (numpy/lib/_function_base_impl.py): a pure
composition of axis flips and a transpose, so the result is always a view that shares
memory with m (read-only when the source is, e.g. a broadcast view).
rot90(m, k=1, axes=(1, 0)) is the reverse of rot90(m, k=1, axes=(0, 1)).
https://numpy.org/doc/stable/reference/generated/numpy.rot90.html
round_(NDArray, int, NDArray, DType)
Evenly round to the given number of decimals.
public static NDArray round_(NDArray x, int decimals = 0, NDArray @out = null, DType dtype = null)
Parameters
xNDArrayInput array.
decimalsintNumber of decimal places to round to (default 0). Half is rounded to even.
outNDArrayA location into which the result is stored; must be the correct shape, returned as-is. np.round/np.around are FUNCTIONS, not ufuncs, so they accept
out=only — there is nowhere=/dtype=ufunc kwarg (probed 2.4.2). Thedtypehere is NumSharp's dtype-target convenience, taken as a keyword.dtypeDTypeThe DType the returned ndarray should be of (a C# Type, an NPTypeCode or a NumPy dtype string all convert implicitly). null preserves NumPy's round dtype rules (integer inputs are an identity copy).
Returns
- NDArray
An array of the same type as a, containing the rounded values. Unless out was specified, a new array is created. A reference to the result is returned. The real and imaginary parts of complex numbers are rounded separately. The result of rounding a float is a float.
Remarks
save(NDArray, bool)
Encode an array as .npy and return the bytes.
public static byte[] save(NDArray arr, bool allow_pickle = true)
Parameters
Returns
- byte[]
Remarks
A NumSharp convenience; NumPy has no in-memory equivalent.
save(Stream, NDArray, bool)
Write an array in .npy format to an open stream.
public static void save(Stream file, NDArray arr, bool allow_pickle = true)
Parameters
fileStreamAn open, writable stream. Written from its current position and left open, so successive calls append — several arrays can share one file and be read back in order by load_npy(Stream, bool, long).
arrNDArrayThe array to save.
allow_pickleboolPresent for NumPy parity; see save(string, NDArray, bool).
Remarks
save(string, NDArray, bool)
Save an array to a .npy binary file.
public static void save(string file, NDArray arr, bool allow_pickle = true)
Parameters
filestringTarget path.
.npyis appended if the name does not already end with it, matching NumPy.arrNDArrayThe array to save. Any layout; a Fortran-contiguous array is stored as such.
allow_pickleboolPresent for NumPy parity. NumSharp has no object dtype, so nothing can reach the pickle path and this never changes the outcome.
Remarks
The file is byte-for-byte what NumPy 2.4.2's own np.save writes for the same array.
https://numpy.org/doc/stable/reference/generated/numpy.save.html
Exceptions
- NotSupportedException
The dtype has no NumPy equivalent — Decimal.
save(string, Array, bool)
Save an array to a .npy file, converting arr with
np.asanyarray(in object, Type) first.
public static void save(string file, Array arr, bool allow_pickle = true)
Parameters
Remarks
save_version(Stream, NDArray, FormatVersion?, bool)
Write an array in .npy format using an explicit format version — NumPy's
numpy.lib.format.write_array.
public static void save_version(Stream file, NDArray arr, NpyFormat.FormatVersion? version, bool allow_pickle = true)
Parameters
fileStreamAn open, writable stream.
arrNDArrayThe array to save.
versionNpyFormat.FormatVersion?(1,0), (2,0), (3,0), or null to use the oldest that can hold the header. Version 2.0 widens the header-length field to 4 bytes; 3.0 also switches the header to UTF-8.
allow_pickleboolPresent for NumPy parity; see save(string, NDArray, bool).
Exceptions
- FormatException
The version is not one of (1,0), (2,0) or (3,0).
savetxt(Stream, NDArray, string, string, string, string, string, string, string)
Write a 1-D or 2-D array as text to an open stream. The stream is written from its current
position and left open (the caller owns it), and rows are separated by newline
verbatim — no platform newline translation, matching NumPy's file-handle path.
public static void savetxt(Stream stream, NDArray X, string fmt = "%.18e", string delimiter = " ", string newline = "\n", string header = "", string footer = "", string comments = "# ", string encoding = null)
Parameters
streamStreamXNDArrayfmtstringdelimiterstringnewlinestringheaderstringfooterstringcommentsstringencodingstring
Remarks
savetxt(Stream, NDArray, string[], string, string, string, string, string, string)
Write a 1-D or 2-D array as text to an open stream, with one %-format spec per column.
public static void savetxt(Stream stream, NDArray X, string[] fmt, string delimiter = " ", string newline = "\n", string header = "", string footer = "", string comments = "# ", string encoding = null)
Parameters
streamStreamXNDArrayfmtstring[]delimiterstringnewlinestringheaderstringfooterstringcommentsstringencodingstring
Remarks
savetxt(TextWriter, NDArray, string, string, string, string, string, string)
Write a 1-D or 2-D array as text to an open TextWriter. The writer is left open
and owns its encoding/newline policy; rows are separated by newline verbatim.
public static void savetxt(TextWriter writer, NDArray X, string fmt = "%.18e", string delimiter = " ", string newline = "\n", string header = "", string footer = "", string comments = "# ")
Parameters
writerTextWriterXNDArrayfmtstringdelimiterstringnewlinestringheaderstringfooterstringcommentsstring
Remarks
savetxt(TextWriter, NDArray, string[], string, string, string, string, string)
Write a 1-D or 2-D array to a TextWriter, with one %-format spec per column.
public static void savetxt(TextWriter writer, NDArray X, string[] fmt, string delimiter = " ", string newline = "\n", string header = "", string footer = "", string comments = "# ")
Parameters
writerTextWriterXNDArrayfmtstring[]delimiterstringnewlinestringheaderstringfooterstringcommentsstring
Remarks
savetxt(string, NDArray, string, string, string, string, string, string, string)
Save a 1-D or 2-D array to a text file.
public static void savetxt(string fname, NDArray X, string fmt = "%.18e", string delimiter = " ", string newline = "\n", string header = "", string footer = "", string comments = "# ", string encoding = null)
Parameters
fnamestringTarget path. If it ends in
.gzthe file is written gzip-compressed, as NumPy does.XNDArrayThe 1-D or 2-D array to save (a 0-D or ≥3-D array raises ValueError).
fmtstringA single
%-format spec (%.18e, replicated once per column), or a multi-%format string applied to the whole row (in which casedelimiteris ignored). For a complexXa single spec becomes' (%s+%sj)'per column.delimiterstringString separating columns.
newlinestringString separating rows.
headerstringString written at the beginning of the file, each line prefixed by
comments.footerstringString written at the end of the file, each line prefixed by
comments.commentsstringString prepended to
header/footerlines.encodingstringOutput encoding;
null(default) andbytes/utf-8use UTF-8 with no BOM,latin1uses Latin-1.
Remarks
Byte-for-byte what NumPy 2.4.2's own np.savetxt writes for the same array — including
the Python text-mode newline translation on a filename target: every \n is written as
the platform line separator (\r\n on Windows), so the file matches NumPy on the same
platform. The savetxt(Stream, NDArray, string, string, string, string, string, string, string)
and TextWriter overloads write \n verbatim, matching NumPy's file-handle path.
https://numpy.org/doc/stable/reference/generated/numpy.savetxt.html
savetxt(string, NDArray, string[], string, string, string, string, string, string)
Save a 1-D or 2-D array to a text file, with one %-format spec per column.
public static void savetxt(string fname, NDArray X, string[] fmt, string delimiter = " ", string newline = "\n", string header = "", string footer = "", string comments = "# ", string encoding = null)
Parameters
fnamestringXNDArrayfmtstring[]One format spec per column. Its length must equal the number of columns, else AttributeError is raised. For a complex array each entry must itself contain both the real and imaginary specs (e.g.
"%.3e%+.3ej").delimiterstringnewlinestringheaderstringfooterstringcommentsstringencodingstring
Remarks
savez(params NDArray[])
Encode an uncompressed .npz archive of arr_0… arrays and return the bytes.
public static byte[] savez(params NDArray[] args)
Parameters
argsNDArray[]
Returns
- byte[]
Remarks
A NumSharp convenience; NumPy has no in-memory equivalent.
savez(IDictionary<string, NDArray>)
Encode an uncompressed .npz archive of named arrays and return the bytes.
public static byte[] savez(IDictionary<string, NDArray> kwds)
Parameters
kwdsIDictionary<string, NDArray>
Returns
- byte[]
Remarks
A NumSharp convenience; NumPy has no in-memory equivalent.
savez(Stream, params NDArray[])
Write an uncompressed .npz archive to an open stream.
public static void savez(Stream file, params NDArray[] args)
Parameters
Remarks
savez(Stream, NDArray[], IDictionary<string, NDArray>, bool)
Write an uncompressed .npz archive of positional and named arrays to an open stream.
public static void savez(Stream file, NDArray[] args, IDictionary<string, NDArray> kwds, bool allow_pickle = true)
Parameters
fileStreamargsNDArray[]kwdsIDictionary<string, NDArray>allow_pickleboolPresent for NumPy parity; a no-op — see savez(string, NDArray[], IDictionary<string, NDArray>, bool).
Remarks
savez(Stream, IDictionary<string, NDArray>)
Write an uncompressed .npz archive of named arrays to an open stream.
public static void savez(Stream file, IDictionary<string, NDArray> kwds)
Parameters
fileStreamkwdsIDictionary<string, NDArray>
Remarks
savez(string, params NDArray[])
Save several arrays into an uncompressed .npz archive, named arr_0,
arr_1, … in order.
public static void savez(string file, params NDArray[] args)
Parameters
filestringTarget path.
.npzis appended if not already present.argsNDArray[]The arrays, in order.
Remarks
savez(string, NDArray[], IDictionary<string, NDArray>, bool)
Save positional and named arrays into an uncompressed .npz archive.
public static void savez(string file, NDArray[] args, IDictionary<string, NDArray> kwds, bool allow_pickle = true)
Parameters
filestringTarget path.
.npzis appended if not already present.argsNDArray[]Positional arrays, stored as
arr_0,arr_1, …kwdsIDictionary<string, NDArray>Named arrays.
allow_pickleboolPresent for NumPy parity (its signature is
savez(file, *args, allow_pickle=True, **kwds)). NumSharp has no object dtype, so nothing can reach the pickle path and this never changes the outcome.
Remarks
Exceptions
- ArgumentException
A name in
kwdscollides with a generatedarr_N.
savez(string, IDictionary<string, NDArray>)
Save named arrays into an uncompressed .npz archive — NumPy's keyword form,
np.savez(file, weights=w, biases=b).
public static void savez(string file, IDictionary<string, NDArray> kwds)
Parameters
filestringTarget path.
.npzis appended if not already present.kwdsIDictionary<string, NDArray>Name/array pairs. Each becomes
<name>.npyin the archive.
Remarks
savez_compressed(params NDArray[])
Encode a compressed .npz archive of arr_0… arrays and return the bytes.
public static byte[] savez_compressed(params NDArray[] args)
Parameters
argsNDArray[]
Returns
- byte[]
Remarks
A NumSharp convenience; NumPy has no in-memory equivalent.
savez_compressed(IDictionary<string, NDArray>)
Encode a compressed .npz archive of named arrays and return the bytes.
public static byte[] savez_compressed(IDictionary<string, NDArray> kwds)
Parameters
kwdsIDictionary<string, NDArray>
Returns
- byte[]
Remarks
A NumSharp convenience; NumPy has no in-memory equivalent.
savez_compressed(Stream, params NDArray[])
Write a compressed .npz archive to an open stream.
public static void savez_compressed(Stream file, params NDArray[] args)
Parameters
Remarks
savez_compressed(Stream, NDArray[], IDictionary<string, NDArray>, bool)
Write a compressed .npz archive of positional and named arrays to an open stream.
public static void savez_compressed(Stream file, NDArray[] args, IDictionary<string, NDArray> kwds, bool allow_pickle = true)
Parameters
fileStreamargsNDArray[]kwdsIDictionary<string, NDArray>allow_pickleboolPresent for NumPy parity; a no-op — see savez(string, NDArray[], IDictionary<string, NDArray>, bool).
Remarks
savez_compressed(Stream, IDictionary<string, NDArray>)
Write a compressed .npz archive of named arrays to an open stream.
public static void savez_compressed(Stream file, IDictionary<string, NDArray> kwds)
Parameters
fileStreamkwdsIDictionary<string, NDArray>
Remarks
savez_compressed(string, params NDArray[])
Save several arrays into a compressed .npz archive, named arr_0,
arr_1, … in order.
public static void savez_compressed(string file, params NDArray[] args)
Parameters
filestringTarget path.
.npzis appended if not already present.argsNDArray[]The arrays, in order.
Remarks
savez_compressed(string, NDArray[], IDictionary<string, NDArray>, bool)
Save positional and named arrays into a compressed .npz archive.
public static void savez_compressed(string file, NDArray[] args, IDictionary<string, NDArray> kwds, bool allow_pickle = true)
Parameters
filestringargsNDArray[]kwdsIDictionary<string, NDArray>allow_pickleboolPresent for NumPy parity; a no-op — see savez(string, NDArray[], IDictionary<string, NDArray>, bool).
Remarks
savez_compressed(string, IDictionary<string, NDArray>)
Save named arrays into a compressed .npz archive.
public static void savez_compressed(string file, IDictionary<string, NDArray> kwds)
Parameters
filestringkwdsIDictionary<string, NDArray>
Remarks
sctype2char(NPTypeCode)
Return the string representation of a scalar dtype.
public static char sctype2char(NPTypeCode sctype)
Parameters
sctypeNPTypeCodeA scalar type.
Returns
- char
The character code for the type.
Examples
np.sctype2char(NPTypeCode.Int32) // 'i'
np.sctype2char(NPTypeCode.Double) // 'd'
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.sctype2char.html
Character codes (NumPy): '?' - boolean 'b' - int8 (signed byte) 'B' - uint8 (unsigned byte) 'h' - int16 (short) 'H' - uint16 (unsigned short) 'i' - int32 'I' - uint32 'q' - int64 'Q' - uint64 'e' - float16 (Half) 'f' - float32 'd' - float64 'D' - complex128
searchsorted(NDArray, NDArray, string, NDArray)
Find indices where elements should be inserted to maintain order.
Find the indices into a sorted array a such that, if the corresponding elements
in v were inserted before the indices, the order of a would be preserved.
public static NDArray searchsorted(NDArray a, NDArray v, string side = "left", NDArray sorter = null)
Parameters
aNDArrayInput 1-D array. Must be sorted ascending unless
sorteris provided.vNDArrayValues to insert into
a. May be a scalar or any shape.sidestringIf "left" (default), the index of the first suitable location is returned. If "right", the last such index.
sorterNDArrayOptional indices that sort
ainto ascending order (typicallyargsort(a)).
Returns
- NDArray
Array of insertion points with the same shape as
v, or a scalar ifvis a scalar.
Remarks
searchsorted(NDArray, double, string, NDArray)
Find index where a scalar should be inserted to maintain order.
public static long searchsorted(NDArray a, double v, string side = "left", NDArray sorter = null)
Parameters
Returns
searchsorted(NDArray, int, string, NDArray)
Find index where a scalar should be inserted to maintain order.
public static long searchsorted(NDArray a, int v, string side = "left", NDArray sorter = null)
Parameters
aNDArrayInput 1-D array. Must be sorted ascending unless
sorteris provided.vintValue to insert into
a.sidestringIf "left" (default), index of the first suitable location is returned. If "right", the last such index.
sorterNDArrayOptional indices that sort
ainto ascending order (typicallyargsort(a)).
Returns
- long
Scalar index for insertion point.
Remarks
select(NDArray[], object[], object)
Return an array drawn from elements in choicelist, depending on
condlist. The output at position m is the m-th element
of the array in choicelist where the m-th element of the
corresponding array in condlist is true. When multiple
conditions are satisfied, the FIRST one encountered in condlist wins;
positions where every condition is false take default.
public static NDArray select(NDArray[] condlist, object[] choicelist, object @default = null)
Parameters
condlistNDArray[]The conditions that determine which array in
choicelisteach output element is taken from. Must be boolean arrays and the same length aschoicelist. All conditions are broadcast against each other.choicelistobject[]The arrays the output elements are drawn from. Each entry is either an NDArray (strong dtype) or a boxed C# scalar. As in NumPy (NEP50), an
int/float/double/Complex literal is a weak scalar that adopts the other operands' dtype, whilebool,char, Half,decimal, arrays and every NDArray are strong. An NDArray[] binds here directly via array covariance; scalar choices need an explicitnew object[] { … }. All choices ANDdefaultare broadcast against each other.defaultobjectThe value inserted where all conditions are
false.null(the C# default) is NumPy'sdefault=0— a weak python int. Accepts a scalar or an NDArray (which participates in the choice broadcast shape).
Returns
- NDArray
A fresh C-contiguous array whose dtype is result_type(params object[]) of every choice and the default (NEP50), and whose shape is the broadcast of the conditions against the choices.
Remarks
Port of NumPy 2.x numpy.select (numpy/lib/_function_base_impl.py): fill the
result with the default, then copyto(NDArray, NDArray, string, NDArray) each choice onto it under its
condition mask in REVERSE order so the first matching condition takes precedence — the
same composition NumPy uses, so every masked write rides NumSharp's SIMD masked-cast
kernel. The contiguous, no-cast, full-size-array-choice case (the one NumPy leaves
memory-bound, since its (n+1) masked copytos each re-read and re-write the whole result)
is instead served by a fused single-pass IL kernel — see
GetSelectKernel(NPTypeCode, int, bool).
https://numpy.org/doc/stable/reference/generated/numpy.select.html
Exceptions
- ValueError
condlistandchoicelistdiffer in length, orcondlistis empty.- TypeError
A condition is not a boolean array.
- IncorrectShapeException
The conditions, the choices, or the two groups against each other cannot be broadcast (NumSharp's house form of NumPy's broadcast
ValueError).
set_printoptions(int?, int?, int?, int?, bool?, string, string, char?, string)
Set printing options (NumPy's np.set_printoptions). These options determine the
way floating point numbers, arrays and other NumPy objects are displayed.
public static void set_printoptions(int? precision = null, int? threshold = null, int? edgeitems = null, int? linewidth = null, bool? suppress = null, string nanstr = null, string infstr = null, char? sign = null, string floatmode = null)
Parameters
precisionint?thresholdint?edgeitemsint?linewidthint?suppressbool?nanstrstringinfstrstringsignchar?floatmodestring
Remarks
setbufsize(long)
Set the size of the buffer used in ufuncs (the default buffer size for buffered NDIter/ufunc iteration on the calling thread) and return the previous size.
public static long setbufsize(long size)
Parameters
sizelongNew buffer size in elements. Must be non-negative, at most 10,000,000, at least 5, and a multiple of 16 — so the smallest accepted value is 16.
Returns
- long
The buffer size in effect before this call.
Remarks
Mirrors numpy.setbufsize(size). The setting is thread-local (matching NumPy
2.x's context-local buffer state) and persists until changed again on the same thread; it
never affects other threads. Buffering is purely a performance/chunking knob, so changing
it leaves every computed result bit-for-bit identical.
Unlike NumPy — which accepts any Python int and raises TypeError for a
float/bool and OverflowError for a value beyond the platform integer —
C#'s type system already rejects a non-integer argument at compile time, so only the
value-range ValueErrors remain reachable.
Exceptions
- ValueError
If
sizeis invalid. The message and the order in which the checks run match NumPy verbatim: negative →"buffer size must be non-negative"; greater than 10,000,000 →"Buffer size, {size}, is too big"; less than 5 →"Buffer size, {size}, is too small"; not a multiple of 16 →"Buffer size, {size}, is not a multiple of 16".
setdiff1d(NDArray, NDArray, bool)
Find the set difference of two arrays.
Return the unique values in ar1 that are not in ar2.
public static NDArray setdiff1d(NDArray ar1, NDArray ar2, bool assume_unique = false)
Parameters
ar1NDArrayInput array.
ar2NDArrayInput comparison array.
assume_uniqueboolIf True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.
Returns
- NDArray
1-D array of values in
ar1that are not inar2. Sorted whenassume_uniqueis False.
Remarks
setxor1d(NDArray, NDArray, bool)
Find the set exclusive-or of two arrays.
Return the sorted, unique values that are in only one (not both) of the input arrays.
public static NDArray setxor1d(NDArray ar1, NDArray ar2, bool assume_unique = false)
Parameters
ar1NDArrayInput array.
ar2NDArrayInput array.
assume_uniqueboolIf True, the input arrays are both assumed to be unique, which can speed up the calculation. Default is False.
Returns
- NDArray
Sorted 1-D array of unique values that are in only one of the input arrays.
Remarks
sign(NDArray, NDArray, NDArray, DType)
public static NDArray sign(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
sin(NDArray, NDArray, NDArray, DType)
Trigonometric sine, element-wise.
Mirrors NumPy's ufunc signature: sin(x, /, out=None, *, where=True, dtype=None).
public static NDArray sin(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayAngle, in radians (2 \pi rad equals 360 degrees).
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs at this precision; integer/bool requests raise NumPy's "No loop matching" error.
Returns
- NDArray
The sine of each element of x. This is a scalar if x is a scalar.
Remarks
sinh(NDArray, NDArray, NDArray, DType)
Hyperbolic sine, element-wise.
Equivalent to 1/2 * (np.exp(x) - np.exp(-x)) or -1j * np.sin(1j*x).
public static NDArray sinh(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of, only non integer values are supported.
Returns
- NDArray
The sine of each element of x. This is a scalar if x is a scalar.
Remarks
size(NDArray, int?)
Return the number of elements along a given axis.
public static long size(NDArray a, int? axis = null)
Parameters
aNDArrayInput data.
axisint?Axis along which the elements are counted. By default, give the total number of elements.
Returns
- long
Number of elements along the specified axis.
Remarks
sort(NDArray, int?, string)
Return a sorted copy of an array, sorted along axis
(default last; null flattens first). NumPy np.sort.
public static NDArray sort(NDArray a, int? axis = -1, string kind = null)
Parameters
aNDArrayArray to sort.
axisint?Axis to sort along. -1 = last axis. null = sort the flattened array.
kindstringSort algorithm name (NumPy compatibility). All kinds produce identical sorted output; the kernel is a stable LSD radix (numeric) or BCL introsort (Half/Complex/Decimal).
Returns
Remarks
NaN floats sort to the end; complex sorts lexicographically (real then imaginary), any-NaN-part last — matching NumPy 2.4.2.
sort_complex(NDArray)
Sort a complex array using the real part first, then the imaginary part.
Port of NumPy's numpy/lib/_function_base_impl.py: b = array(a, copy=True);
b.sort() — i.e. sorted along the LAST axis in the input's own dtype — then up-cast
to complex. Always returns a fresh complex array; the input is never mutated.
public static NDArray sort_complex(NDArray a)
Parameters
aNDArrayInput array.
Returns
- NDArray
Sorted complex array (sorted along the last axis).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.sort_complex.html
NumPy widths: int8/uint8/int16/uint16 up-cast to complex64, longdouble to clongdouble,
everything else to complex128; NumSharp has the single Complex
(complex128) width, so every non-complex dtype lands there — the VALUES are identical
(all four narrow-int ranges are exact in float32 and float64 alike), only the width differs.
Char/Decimal (no NumPy analog) take the same route: sort in their own dtype, then cast.
NaN floats sort to the end (→ nan+0j); complex sorts lexicographically with NumPy's
any-NaN-part-last ordering. A 0-d input leaks ndarray.sort()'s own
"axis -1 is out of bounds for array of dimension 0" — exactly as NumPy leaks it.
split(NDArray, int, int)
Split an array into multiple sub-arrays as views into ary.
public static NDArray[] split(NDArray ary, int indices_or_sections, int axis = 0)
Parameters
aryNDArrayArray to be divided into sub-arrays.
indices_or_sectionsintIf an integer, N, the array will be divided into N equal arrays along axis. If such a split is not possible, an error is raised.
axisintThe axis along which to split, default is 0.
Returns
- NDArray[]
A list of sub-arrays as views into ary.
Remarks
Exceptions
- ArgumentException
If indices_or_sections is an integer and does not result in equal division.
split(NDArray, int[], int)
Split an array into multiple sub-arrays as views into ary.
public static NDArray[] split(NDArray ary, int[] indices, int axis = 0)
Parameters
Returns
- NDArray[]
split(NDArray, long[], int)
Split an array into multiple sub-arrays as views into ary.
public static NDArray[] split(NDArray ary, long[] indices, int axis = 0)
Parameters
Returns
- NDArray[]
sqrt(NDArray, NDArray, NDArray, DType)
Return the non-negative square-root of an array, element-wise.
Mirrors NumPy's ufunc signature: sqrt(x, /, out=None, *, where=True, dtype=None).
public static NDArray sqrt(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayThe values whose square-roots are required.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs at this precision; integer/bool requests raise NumPy's "No loop matching" error.
Returns
- NDArray
An array of the same shape as x, containing the positive square-root of each element in x. If any element in x is complex, a complex array is returned (and the square-roots of negative reals are calculated). If all of the elements in x are real, so is y, with negative elements returning nan. If out was provided, y is a reference to it. This is a scalar if x is a scalar.
Remarks
square(NDArray)
Return the element-wise square of the input.
public static NDArray square(NDArray x)
Parameters
xNDArrayInput data.
Returns
- NDArray
Element-wise x*x, of the same shape and dtype as x. Returns scalar if x is a scalar.
Remarks
square(NDArray, NDArray, NDArray, DType)
Return the element-wise square of the input.
Mirrors NumPy's ufunc signature: square(x, /, out=None, *, where=True, dtype=None).
public static NDArray square(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput data.
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the input must be same_kind-castable to it.
Returns
Remarks
squeeze(NDArray)
Remove single-dimensional entries from the shape of an array.
public static NDArray squeeze(NDArray a)
Parameters
aNDArrayInput data.
Returns
- NDArray
The input array, but with all or a subset of the dimensions of length 1 removed. This is always a itself or a view into a.
Remarks
A pure VIEW like NumPy's PyArray_Squeeze: the length-one axes are dropped from the
dims AND strides while offset/buffer stay — never a reshape (which rebuilds C-strides and
so lost F-contiguity, and MATERIALIZED non-contiguous inputs where NumPy shares memory).
Probed: np.asfortranarray(zeros((3,1,4))).squeeze() is F-contiguous, a transposed
input stays a strided view, and a broadcast input keeps stride-0 (read-only).
https://numpy.org/doc/stable/reference/generated/numpy.squeeze.html
squeeze(NDArray, int)
Remove single-dimensional entries from the shape of an array.
public static NDArray squeeze(NDArray a, int axis)
Parameters
aNDArrayInput data.
axisintSelects a subset of the single-dimensional entries in the shape. If an axis is selected with shape entry greater than one, an error is raised.
Returns
- NDArray
The input array, but with all or a subset of the dimensions of length 1 removed. This is always a itself or a view into a.
Remarks
Exceptions
- IncorrectShapeException
If axis is not None, and an axis being squeezed is not of length 1
squeeze(Shape)
Remove single-dimensional entries from a shape.
public static Shape squeeze(Shape shape)
Parameters
shapeShapeInput shape.
Returns
- Shape
The input array, but with all or a subset of the dimensions of length 1 removed. This is always a itself or a view into a.
Remarks
stack(NDArray[], int)
Join a sequence of arrays along a new axis. The axis parameter specifies the index of the new axis in the dimensions of the result. For example, if axis=0 it will be the first dimension and if axis=-1 it will be the last dimension.
public static NDArray stack(NDArray[] arrays, int axis = 0)
Parameters
arraysNDArray[]Each array must have the same shape.
axisintThe axis in the result array along which the input arrays are stacked.
Returns
- NDArray
The stacked array has one more dimension than the input arrays.
Remarks
std(NDArray, bool, int?, DType)
Compute the standard deviation of the flattened array. Returns the standard deviation, a measure of the spread of a distribution, of the array elements.
public static NDArray std(NDArray a, bool keepdims = false, int? ddof = null, DType dtype = null)
Parameters
aNDArrayCalculate the standard deviation of these values.
keepdimsboolIf true, the reduced axes are left in the result as size-one dimensions.
ddofint?Delta Degrees of Freedom. The divisor used is N - ddof (default 0).
dtypeDTypeThe DType the computation/result should use (a C# Type, an NPTypeCode or a NumPy dtype string all convert implicitly).
Returns
- NDArray
A new array containing the std values, or a reference to the output array.
Remarks
std(NDArray, int, bool, int?, DType)
Compute the standard deviation along the specified axis.
public static NDArray std(NDArray a, int axis, bool keepdims = false, int? ddof = null, DType dtype = null)
Parameters
aNDArrayCalculate the standard deviation of these values.
axisintAxis along which the standard deviation is computed.
keepdimsboolIf true, the reduced axes are left in the result as size-one dimensions.
ddofint?Delta Degrees of Freedom. The divisor used is N - ddof (default 0).
dtypeDTypeThe DType the computation/result should use (implicit from Type / NPTypeCode / NumPy dtype string).
Returns
- NDArray
A new array containing the std values, or a reference to the output array.
Remarks
subtract(NDArray, NDArray, NDArray, NDArray, DType)
public static NDArray subtract(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
Remarks
sum(NDArray)
Sum of all array elements.
public static NDArray sum(NDArray a)
Parameters
aNDArrayElements to sum.
Returns
- NDArray
A scalar (0-d) sum of the flattened array.
Remarks
sum(NDArray, DType)
Sum of array elements in a given dtype (the accumulator/return type).
public static NDArray sum(NDArray a, DType dtype)
Parameters
aNDArrayElements to sum.
dtypeDTypeThe DType of the accumulator/return (a C# Type, an NPTypeCode or a NumPy dtype string all convert implicitly). By default NumPy's NEP50 accumulator rules apply (e.g. int32 → int64).
Returns
Remarks
sum(NDArray, bool)
Sum of all array elements, optionally keeping the reduced dimensions.
public static NDArray sum(NDArray a, bool keepdims)
Parameters
aNDArrayElements to sum.
keepdimsboolIf true, the reduced axes are left in the result as size-one dimensions.
Returns
Remarks
sum(NDArray, int)
Sum of array elements over the given axis.
public static NDArray sum(NDArray a, int axis)
Parameters
aNDArrayElements to sum.
axisintAxis along which a sum is performed (negative counts from the last axis).
Returns
Remarks
sum(NDArray, int?, DType)
Sum of array elements over the given axis in a given dtype.
public static NDArray sum(NDArray a, int? axis, DType dtype)
Parameters
aNDArrayElements to sum.
axisint?Axis along which a sum is performed (null sums the flattened array).
dtypeDTypeThe DType of the accumulator/return (implicit from Type / NPTypeCode / NumPy dtype string).
Returns
Remarks
sum(NDArray, int?, bool)
Sum of array elements over the given axis, optionally keeping the reduced dimensions.
public static NDArray sum(NDArray a, int? axis, bool keepdims)
Parameters
aNDArrayElements to sum.
axisint?Axis along which a sum is performed (null sums the flattened array).
keepdimsboolIf true, the reduced axes are left in the result as size-one dimensions.
Returns
Remarks
sum(NDArray, int?, bool, DType)
Sum of array elements over the given axis in a given dtype, optionally keeping the reduced dimensions.
public static NDArray sum(NDArray a, int? axis, bool keepdims, DType dtype)
Parameters
aNDArrayElements to sum.
axisint?Axis along which a sum is performed (null sums the flattened array).
keepdimsboolIf true, the reduced axes are left in the result as size-one dimensions.
dtypeDTypeThe DType of the accumulator/return (implicit from Type / NPTypeCode / NumPy dtype string).
Returns
Remarks
swapaxes(NDArray, int, int)
Interchange two axes of an array.
public static NDArray swapaxes(NDArray a, int axis1, int axis2)
Parameters
Returns
Remarks
take(NDArray, NDArray, int?, NDArray, string)
Take elements from an array along an axis. Equivalent to fancy indexing along the specified axis.
public static NDArray take(NDArray a, NDArray indices, int? axis = null, NDArray @out = null, string mode = "raise")
Parameters
aNDArraySource array.
indicesNDArrayInteger array of indices to take.
axisint?Axis along which to take.
null(default) flattensaand treatsindicesas flat indices.outNDArrayOptional destination array. When supplied, its shape must match the natural take output; values are cast to
out's dtype via copyto(NDArray, NDArray, string, NDArray) with unsafe casting and the method returnsoutitself. Whennull(default), a fresh array is allocated witha's dtype.modestringBoundary mode:
"raise"(default — throw on OOB),"wrap"(modulo with sign correction), or"clip"(saturate).
Returns
- NDArray
New array with shape:
axis=None: same asindices.axis=k:a.shape[:k] + indices.shape + a.shape[k+1:].
Dtype matches
a(orout's dtype whenoutis supplied).
Remarks
take(NDArray, long, int?, NDArray, string)
Scalar convenience overload — take a single element by flat index.
public static NDArray take(NDArray a, long index, int? axis = null, NDArray @out = null, string mode = "raise")
Parameters
Returns
take_along_axis(NDArray, NDArray, int?)
Take values from the input array by matching 1-D index and data slices.
Iterates over matching 1-D slices oriented along axis in the
index and data arrays, using the former to look up values in the latter. These
slices can be different lengths. Functions returning an index along an axis, like
argsort(NDArray,int?,string) and argmax/argmin with
keepdims, produce suitable indices.
public static NDArray take_along_axis(NDArray arr, NDArray indices, int? axis = -1)
Parameters
arrNDArraySource array
(Ni..., M, Nk...).indicesNDArrayInteger index array
(Ni..., J, Nk...). Must match the dimension count ofarr; the non-axis dimensionsNi/Nkonly need to broadcast againstarr.axisint?The axis to take 1-D slices along (default
-1, matching NumPy 2.3+). Whennullthe source is treated as if first flattened to 1-D in C-order, for consistency withsort/argsort; thenindicesmust be 1-D.
Returns
- NDArray
A fresh C-contiguous array of shape
(Ni..., J, Nk...)(the broadcast of the non-axis dimensions, withJ = indices.shape[axis]) and dtype ofarr.
Remarks
tan(NDArray, NDArray, NDArray, DType)
Compute tangent element-wise.
Equivalent to np.sin(x)/np.cos(x) element-wise.
Mirrors NumPy's ufunc signature: tan(x, /, out=None, *, where=True, dtype=None).
public static NDArray tan(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayAngle, in radians (2 \pi rad equals 360 degrees).
outNDArraywhereNDArrayBoolean mask: only mask-true elements are computed/written (NumPy ufunc where=).
dtypeDTypeExplicit loop dtype (NumPy ufunc dtype=): the computation runs at this precision; integer/bool requests raise NumPy's "No loop matching" error.
Returns
- NDArray
The tangent of each element of x. This is a scalar if x is a scalar.
Remarks
tanh(NDArray, NDArray, NDArray, DType)
Compute hyperbolic tangent element-wise.
Equivalent to np.sinh(x)/np.cosh(x) or -1j * np.tan(1j*x).
public static NDArray tanh(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of, only non integer values are supported.
Returns
- NDArray
The sine of each element of x. This is a scalar if x is a scalar.
Remarks
tensordot(NDArray, NDArray, int)
Tensor contraction over the given axes — a sum product over the last
axes axes of a and the first
axes of b.
public static NDArray tensordot(NDArray a, NDArray b, int axes = 2)
Parameters
aNDArraybNDArrayaxesintHow many trailing axes of
ato contract against leading axes ofb.0gives the outer (tensor) product;1is dot(NDArray, NDArray, NDArray);2(the default) is the double contraction. A NEGATIVE count contracts nothing — NumPy formsrange(-axes, 0), which is empty for anyaxes <= 0.
Returns
Remarks
tensordot(NDArray, NDArray, int[], int[])
Tensor contraction pairing axesA of a with
axesB of b, element by element — NumPy's
axes=(list, list) spelling.
public static NDArray tensordot(NDArray a, NDArray b, int[] axesA, int[] axesB)
Parameters
Returns
Exceptions
- ValueError
"duplicate axes are not allowed in tensordot"when either list repeats a raw axis value (checked first, ahead of everything), or"shape-mismatch for sum"for unequal list lengths and mismatched contracted extents alike.- IndexError
"tuple index out of range"when a contraction axis is out of range — NumPy indexes the shape tuple with the raw axis, so this is an index error, not a shape mismatch. A mismatched extent found earlier in the list settles as the shape mismatch first, hiding a later out-of-range axis.
tensordot(NDArray, NDArray, (int AxisA, int AxisB))
Tensor contraction pairing one axis of a with one of
b — NumPy's axes=(int, int) spelling.
public static NDArray tensordot(NDArray a, NDArray b, (int AxisA, int AxisB) axes)
Parameters
Returns
tile(NDArray, params int[])
Construct an array by repeating A the number of times given by reps.
If reps has length d, the result has dimension max(d, A.ndim).
If A.ndim < d, A is promoted to be d-dimensional by prepending size-1 axes.
If A.ndim > d, reps is promoted to A.ndim by prepending 1s.
public static NDArray tile(NDArray A, params int[] reps)
Parameters
ANDArrayThe input array.
repsint[]The number of repetitions of A along each axis. Each rep must be non-negative.
Returns
- NDArray
The tiled output array. Expanded outputs are C-contiguous; all-one reps produce a keep-order copy. Dtype matches
A.
Remarks
Exceptions
- ArgumentNullException
If
Aorrepsis null.- ArgumentException
If any element of
repsis negative.
tile(NDArray, long[])
Construct an array by repeating A the number of times given by reps.
Long overload — see tile(NDArray, params int[]).
public static NDArray tile(NDArray A, long[] reps)
Parameters
Returns
trace(NDArray, int, int, int, DType, NDArray)
Return the sum along diagonals of the array. For a 2-D array,
trace(a) == sum(a.diagonal()). For an N-D array, traces
the diagonals along the 2-D sub-arrays defined by
axis1 / axis2 and reduces
them, leaving an array with those two axes removed.
public static NDArray trace(NDArray a, int offset = 0, int axis1 = 0, int axis2 = 1, DType dtype = null, NDArray @out = null)
Parameters
aNDArraySource array. Must have at least 2 dimensions.
offsetintOffset of the diagonal from the main diagonal. See diagonal(NDArray, int, int, int) for details.
axis1intFirst axis of the 2-D sub-array. Default 0.
axis2intSecond axis of the 2-D sub-array. Default 1.
dtypeDTypeOutput dtype.
null(default) preservesa.dtype, except integer dtypes narrower than long promote to long (NEP50 / matches NumPy's "default platform integer" rule). Bool input promotes to long.outNDArrayOptional output array. Shape must equal the natural reduction output; values are copied with unsafe casting and the method returns
outitself.
Returns
- NDArray
Sum along the diagonal. 2-D input → 0-d scalar. N-D input → array with
a.shapeminusaxis1andaxis2.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.trace.html
Mirrors NumPy's PyArray_Trace: sum(diagonal(a,
offset, axis1, axis2), axis=-1, dtype=dtype, out=out). The
diagonal view is the heavy lifting; the sum is a regular
reduction that goes through NumSharp's IL reduction kernels.
transpose(NDArray, int[])
Permute the dimensions of an array.
public static NDArray transpose(NDArray a, int[] premute = null)
Parameters
aNDArrayInput array.
premuteint[]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
tri(int, int?, int, DType)
An array with ones at and below the given diagonal and zeros elsewhere.
public static NDArray tri(int N, int? M = null, int k = 0, DType dtype = null)
Parameters
NintNumber of rows in the array.
Mint?Number of columns in the array. By default,
Mis taken equal toN.kintThe sub-diagonal at and below which the array is filled.
k = 0is the main diagonal, whilek < 0is below it, andk > 0is above.dtypeDTypeData type of the returned array. Defaults to double.
Returns
- NDArray
Array with shape
(N, M)whose lower triangle — filled with ones — is at and below thek-th diagonal. Always a freshly allocated, C-contiguous, writeable array.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.tri.html
NumPy computes this as greater_equal.outer(arange(N), arange(-k, M-k))
followed by an astype — two full N×M passes plus a bool temporary.
Because row i is exactly c_i = clamp(i + k + 1, 0, M) ones followed
by zeros, NumSharp instead allocates the (already zeroed) result and blits a
prefix of a single pre-built ones row into each row. That is one
MemoryCopy(void*, void*, long, long) per row over an untouched zero tail — no
comparison kernel, no mask temporary, and completely dtype-agnostic (the copy
only ever sees bytes).
Negative N/M clamp to zero, matching
NumPy (whose arange of a negative count yields an empty axis).
tril(NDArray, int)
Lower triangle of an array — a copy of m with all elements
above the k-th diagonal zeroed.
public static NDArray tril(NDArray m, int k = 0)
Parameters
mNDArrayInput array. For arrays with
ndim > 2,trilapplies to the final two axes.kintDiagonal above which to zero elements.
k = 0(the default) is the main diagonal,k < 0is below it andk > 0is above.
Returns
- NDArray
Lower triangle of
m, of the same dtype. Always a fresh, writeable, C-contiguous array.
Remarks
tril_indices(int, int, int?)
Return the indices for the lower-triangle of an (n, m) array.
public static NDArray<long>[] tril_indices(int n, int k = 0, int? m = null)
Parameters
nintThe row dimension of the arrays for which the returned indices will be valid.
kintDiagonal offset.
k = 0(default) is the main diagonal.mint?The column dimension. By default
mis taken equal ton.
Returns
Remarks
tril_indices_from(NDArray, int)
Return the indices for the lower-triangle of arr.
public static NDArray<long>[] tril_indices_from(NDArray arr, int k = 0)
Parameters
Returns
Remarks
Exceptions
- ArgumentException
input array must be 2-d(NumPyValueError, verbatim).
trim_zeros(NDArray, string, int[])
Remove values which are zero along all other dimensions, trimming the given sequence of axes.
trim is required on this overload so it does not collide with the single-axis
primary above on calls like trim_zeros(filt) / trim_zeros(filt, "f").
public static NDArray trim_zeros(NDArray filt, string trim, int[] axis)
Parameters
filtNDArrayInput array.
trimstringA string with 'f' representing trim from front and 'b' to trim from back. By default, zeros are trimmed on both sides ("fb"). Case-insensitive; "bf" is accepted as an alias of "fb".
axisint[]If
null,filtis cropped to the smallest bounding box that still contains all non-zero values. If axes are specified,filtis sliced in those dimensions only, on the sides selected bytrim. An empty array of axes leaves the input unmodified.
Returns
- NDArray
A view of
filtwith leading/trailing all-zero hyperplanes removed. The number of dimensions and the input dtype are preserved.
Remarks
Exceptions
- ArgumentException
If
trimcontains unexpected characters, or an axis is repeated.- AxisOutOfRangeException
If an axis is out of bounds for
filt.
trim_zeros(NDArray, string, int?)
Remove values along a dimension which are zero along all other dimensions. Mirrors NumPy's
numpy.trim_zeros(filt, trim='fb', axis=None) exactly: axis is a single
axis, or null for the whole-array bounding box. Pass an int[] to trim several axes.
public static NDArray trim_zeros(NDArray filt, string trim = "fb", int? axis = null)
Parameters
filtNDArrayInput array.
trimstring'f' trims from the front, 'b' from the back; "fb" (default) trims both. Case-insensitive.
axisint?The single dimension to trim;
nulltrims the whole-array bounding box.
Returns
Remarks
triu(NDArray, int)
Upper triangle of an array — a copy of m with all elements
below the k-th diagonal zeroed.
public static NDArray triu(NDArray m, int k = 0)
Parameters
mNDArrayInput array. For arrays with
ndim > 2,triuapplies to the final two axes.kintDiagonal below which to zero elements.
k = 0(the default) is the main diagonal,k < 0is below it andk > 0is above.
Returns
- NDArray
Upper triangle of
m, of the same dtype. Always a fresh, writeable, C-contiguous array.
Remarks
triu_indices(int, int, int?)
Return the indices for the upper-triangle of an (n, m) array.
public static NDArray<long>[] triu_indices(int n, int k = 0, int? m = null)
Parameters
nintThe size of the arrays for which the returned indices will be valid.
kintDiagonal offset.
k = 0(default) is the main diagonal.mint?The column dimension. By default
mis taken equal ton.
Returns
Remarks
triu_indices_from(NDArray, int)
Return the indices for the upper-triangle of arr.
public static NDArray<long>[] triu_indices_from(NDArray arr, int k = 0)
Parameters
Returns
Remarks
Exceptions
- ArgumentException
input array must be 2-d(NumPyValueError, verbatim).
true_divide(NDArray, NDArray, NDArray, NDArray, DType)
public static NDArray true_divide(NDArray x1, NDArray x2, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
Returns
Remarks
trunc(NDArray, NDArray, NDArray, DType)
Return the truncated value of the input, element-wise. The truncated value of the scalar x is the nearest integer i which is closer to zero than x is.
public static NDArray trunc(NDArray x, NDArray @out = null, NDArray where = null, DType dtype = null)
Parameters
xNDArrayInput array.
outNDArraywhereNDArraydtypeDTypeThe dtype the returned ndarray should be of.
Returns
- NDArray
The truncated value of each element in x. This is a scalar if x is a scalar.
Remarks
union1d(NDArray, NDArray)
Find the union of two arrays.
Return the unique, sorted array of values that are in either of the two input arrays.
public static NDArray union1d(NDArray ar1, NDArray ar2)
Parameters
ar1NDArrayInput array (flattened if not already 1-D).
ar2NDArrayInput array (flattened if not already 1-D).
Returns
- NDArray
Unique, sorted union of the input arrays.
Remarks
unique(NDArray, bool, bool, bool, int?, bool, bool)
Find the unique elements of an array — the single NumPy-shaped entry point.
Returns the sorted unique elements and, per the return_* flags, the
first-occurrence indices, the reconstruction (inverse) indices, and the per-value counts,
bundled in a np.UniqueResult that stands in for NumPy's bare-array-or-tuple
return. Because np.UniqueResult converts implicitly to both NDArray
and NDArray[], every NumPy call shape ports verbatim — including
np.unique(ar, return_counts: true) and np.unique(ar, axis: 0).
public static np.UniqueResult unique(NDArray ar, bool return_index = false, bool return_inverse = false, bool return_counts = false, int? axis = null, bool equal_nan = true, bool sorted = true)
Parameters
arNDArrayInput array. Unless
axisis given, it is flattened first.return_indexboolIf True, also return the first-occurrence indices of
ar(alongaxisif given) that produce the unique values.return_inverseboolIf True, also return the indices of the unique array that reconstruct
ar.return_countsboolIf True, also return the number of times each unique value appears.
axisint?The axis to operate on. If
null(default), the array is flattened first.equal_nanboolIf True (default), all NaN values collapse to a single output value; if False, each NaN is a distinct value.
sortedboolAccepted for NumPy 2.3 parity; NumSharp always returns sorted output (NumPy's
sorted=Falsehash-iteration order for integer/complex values is platform-specific and not reproducible in C# — spec-compliant, the Array API leaves it unspecified). See unique_values(NDArray).
Returns
- np.UniqueResult
A np.UniqueResult carrying
valuesand the requested outputs.
Remarks
unique_all(NDArray)
Find the unique elements of x together with the first-occurrence indices,
reconstruction indices, and counts.
Array API compatible alternative to np.unique(x, return_index=True, return_inverse=True,
return_counts=True, equal_nan=False). The input is flattened. Each NaN is treated as
a distinct value.
public static np.UniqueAllResult unique_all(NDArray x)
Parameters
xNDArrayInput array. Flattened if it is not already 1-D.
Returns
- np.UniqueAllResult
A np.UniqueAllResult: (values, indices, inverse_indices, counts).
Remarks
unique_counts(NDArray)
Find the unique elements and counts of an input array x.
Array API compatible alternative to np.unique(x, return_counts=True, equal_nan=False).
The input is flattened. Each NaN is treated as a distinct value.
public static np.UniqueCountsResult unique_counts(NDArray x)
Parameters
xNDArrayInput array. Flattened if it is not already 1-D.
Returns
- np.UniqueCountsResult
A np.UniqueCountsResult: (values, counts).
Remarks
unique_inverse(NDArray)
Find the unique elements of x and the indices that reconstruct it.
Array API compatible alternative to np.unique(x, return_inverse=True, equal_nan=False).
The input is flattened. Each NaN is treated as a distinct value.
public static np.UniqueInverseResult unique_inverse(NDArray x)
Parameters
xNDArrayInput array. Flattened if it is not already 1-D.
Returns
- np.UniqueInverseResult
A np.UniqueInverseResult: (values, inverse_indices).
inverse_indiceshas the same shape asx, sonp.take(values, inverse_indices)reconstructs the input.
Remarks
unique_values(NDArray)
Returns the unique elements of an input array x.
Array API compatible alternative to np.unique(x, equal_nan=False, sorted=False).
The input is flattened. Each NaN is treated as a distinct value.
public static NDArray unique_values(NDArray x)
Parameters
xNDArrayInput array. Flattened if it is not already 1-D.
Returns
- NDArray
The unique elements of
x(dtype preserved).
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.unique_values.html
NumSharp returns the values SORTED (like np.unique(x, equal_nan=False)). For integer and
complex dtypes NumPy 2.4.2's sorted=False path returns them in a platform-specific hash
order that is not portable (both contain the same set); float dtypes are sorted on both sides.
The Array API leaves the order unspecified.
unravel_index(NDArray, int[], char)
Converts a flat index or array of flat indices into a tuple of coordinate arrays. Inverse of ravel_multi_index(NDArray[], int[], string, char).
public static NDArray<long>[] unravel_index(NDArray indices, int[] shape, char order = 'C')
Parameters
indicesNDArrayAn integer array whose elements are indices into the flattened version of an array of dimensions
shape. Cast to int64 internally.shapeint[]The shape of the array to use for unraveling.
orderchar'C'(row-major, default) or'F'(column-major) — selects the extraction order for the coordinate tuple.
Returns
- NDArray<long>[]
A tuple of
shape.LengthNDArrays. Each output array has the same shape asindices. Element dtype is always Int64.
Remarks
Exceptions
- ArgumentException
shapeis empty, has non-positive dims, or the dims' product overflows int64.- ArgumentOutOfRangeException
Any index in
indicesis < 0 or= product of
shape.
unravel_index(long, int[], char)
Scalar convenience overload — converts a single flat index into a coord
array. Equivalent to unravel_index(NDArray.Scalar(index), shape, order)
but returns a long[] directly without NDArray wrapping.
public static long[] unravel_index(long index, int[] shape, char order = 'C')
Parameters
Returns
- long[]
unstack(NDArray, int)
Split an array into a sequence of arrays along the given axis.
The axis parameter specifies the dimension along
which the array will be split. For example, if axis=0 (the
default) it will be the first dimension and if axis=-1 it
will be the last dimension.
Added in NumPy 2.1.
public static NDArray[] unstack(NDArray x, int axis = 0)
Parameters
Returns
- NDArray[]
The unstacked arrays —
x.shape[axis]VIEWS intox(shared memory, matching NumPy), each with shape equal tox.shapewith theaxisentry removed.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.unstack.html
unstack serves as the reverse operation of stack(NDArray[], int):
stack(unstack(x, axis), axis) == x. Semantically equivalent to
NumPy's tuple(np.moveaxis(x, axis, 0)) — moving axis
to the front and then indexing it away leaves the remaining axes in
their original relative order, so each view is constructed directly
by dropping axis from dims/strides and advancing the offset
by i * strides[axis]; no iterator or data movement anywhere.
vander(NDArray, int?, bool)
Generate a Vandermonde matrix.
The columns of the output matrix are powers of the input vector. When
increasing is false (the default) the i-th output column is
the input vector raised element-wise to the power of N - i - 1.
public static NDArray vander(NDArray x, int? N = null, bool increasing = false)
Parameters
xNDArray1-D input array.
Nint?Number of columns. If
null, a square matrix is returned (N = len(x)).increasingboolIf
truethe powers increase left to right (x^0 ... x^(N-1)); iffalsethey are reversed (first columnx^(N-1)).
Returns
- NDArray
The Vandermonde matrix, shape
(len(x), N).
Remarks
var(NDArray, bool, int?, DType)
Compute the variance of the flattened array. Returns the variance, a measure of the spread of a distribution, of the array elements.
public static NDArray var(NDArray a, bool keepdims = false, int? ddof = null, DType dtype = null)
Parameters
aNDArrayCalculate the variance of these values.
keepdimsboolIf true, the reduced axes are left in the result as size-one dimensions.
ddofint?Delta Degrees of Freedom. The divisor used is N - ddof (default 0).
dtypeDTypeThe DType the computation/result should use (a C# Type, an NPTypeCode or a NumPy dtype string all convert implicitly).
Returns
- NDArray
A new array containing the variance values, or a reference to the output array.
Remarks
var(NDArray, int, bool, int?, DType)
Compute the variance along the specified axis.
public static NDArray var(NDArray a, int axis, bool keepdims = false, int? ddof = null, DType dtype = null)
Parameters
aNDArrayCalculate the variance of these values.
axisintAxis along which the variance is computed.
keepdimsboolIf true, the reduced axes are left in the result as size-one dimensions.
ddofint?Delta Degrees of Freedom. The divisor used is N - ddof (default 0).
dtypeDTypeThe DType the computation/result should use (implicit from Type / NPTypeCode / NumPy dtype string).
Returns
- NDArray
A new array containing the variance values, or a reference to the output array.
Remarks
vdot(NDArray, NDArray)
Dot product of two vectors, flattening both operands and conjugating the first.
public static NDArray vdot(NDArray a, NDArray b)
Parameters
Returns
- NDArray
A 0-d result, always —
vdotnever performs a matrix product.
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.vdot.html
Two differences from dot(NDArray, NDArray, NDArray): the first argument is replaced by its complex conjugate, and multi-dimensional operands are flattened rather than multiplied as matrices — so for two 2-D operands of the same shape this is their Frobenius inner product.
A length mismatch reports a RESHAPE error, not a length one. NumPy's
array_vdot flattens both operands through one reused PyArray_Dims buffer
holding a single -1; _fix_unknown_dimension writes the resolved length
back into that buffer, so the second flatten asks for (a.size,) rather than
(-1,). np.vdot(ones(3), ones(5)) therefore raises "cannot reshape array
of size 5 into shape (3,)", and the "vectors have different lengths" check that
follows it in the C source is unreachable.
vecdot(NDArray, NDArray, NDArray, int[][], int?, bool, DType)
Vector dot product of two arrays (NumPy 2.0) — the gufunc (n),(n)->(),
conjugating the first operand.
public static NDArray vecdot(NDArray x1, NDArray x2, NDArray @out = null, int[][] axes = null, int? axis = null, bool keepdims = false, DType dtype = null)
Parameters
x1NDArrayFirst operand. Conjugated when complex.
x2NDArraySecond operand.
outNDArrayWhere to deposit the answer. Returned as-is when given.
axesint[][]Which axes carry the core dimensions, per operand:
{x1, x2, out}. The output entry may be omitted here —vecdot's output has no core axes. Cannot be combined withaxis.axisint?The shared core axis, in place of the default last one. Applied to both operands — the special case of
axesthat this signature admits because both core dimensions are the SAME one.keepdimsboolLeave the contracted axis in the result with length 1.
dtypeDTypeSelects the LOOP: computation runs at this dtype, not merely the result.
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.vecdot.html
Unlike sum(NDArray), the accumulation happens in the LOOP dtype rather than
NEP50's wider accumulator: vecdot's registered loops are 'ii->i', so an
int32 pair reduces to int32 where np.sum would give int64.
Core dimensions do NOT broadcast — a length-1 core axis against a length-3 one is an error. Only the leading (loop) axes broadcast.
NumPy's remaining ufunc keywords — casting, order, subok and
signature — are not modelled anywhere in NumSharp's ufunc surface and so are
absent here too rather than accepted and ignored. signature is what
dtype already does; subok concerns ndarray subclasses,
which NumSharp does not have.
vecmat(NDArray, NDArray, NDArray, int[][], int?, bool, DType)
Vector-matrix product (NumPy 2.2) — the gufunc (n),(n,m)->(m), conjugating the
vector operand.
public static NDArray vecmat(NDArray x1, NDArray x2, NDArray @out = null, int[][] axes = null, int? axis = null, bool keepdims = false, DType dtype = null)
Parameters
x1NDArrayVector operand, at least 1-D. Conjugated when complex.
x2NDArrayMatrix operand, at least 2-D. Leading axes broadcast.
outNDArrayWhere to deposit the answer. Returned as-is when given.
axesint[][]Which axes carry the core dimensions, per operand:
{(n), (n,m), (m)}. All THREE entries are required — the output has a core axis.axisint?Present for signature parity only. NumPy raises
TypeErrorfor any value — this signature's core dimensions are two DISTINCT ones; useaxes.keepdimsboolPresent for signature parity only. NumPy raises
TypeErrorwhen true.dtypeDTypeSelects the LOOP: computation runs at this dtype, not merely the result.
Returns
Remarks
https://numpy.org/doc/stable/reference/generated/numpy.vecmat.html
The conjugation is what makes this the adjoint of matvec(NDArray, NDArray, NDArray, int[][], int?, bool, DType) rather than its
mirror image: vecmat(v, m) is conj(v) @ m, so for real operands it is the
plain row-vector product and for complex ones it agrees with vecdot(NDArray, NDArray, NDArray, int[][], int?, bool, DType)'s
convention.
NumPy's remaining ufunc keywords (casting, order, subok,
signature) are not modelled anywhere in NumSharp's ufunc surface and are
absent here too. See vecdot(NDArray, NDArray, NDArray, int[][], int?, bool, DType).
vsplit(NDArray, int)
Split an array into multiple sub-arrays vertically (row-wise).
public static NDArray[] vsplit(NDArray ary, int indices_or_sections)
Parameters
aryNDArrayArray to be divided into sub-arrays.
indices_or_sectionsintIf an integer, N, the array will be divided into N equal arrays along axis 0. If such a split is not possible, an error is raised.
Returns
- NDArray[]
A list of sub-arrays as views into ary.
Remarks
Equivalent to split with axis=0. Array must have ndim >= 2. https://numpy.org/doc/stable/reference/generated/numpy.vsplit.html
vsplit(NDArray, int[])
Split an array into multiple sub-arrays vertically (row-wise).
public static NDArray[] vsplit(NDArray ary, int[] indices)
Parameters
aryNDArrayArray to be divided into sub-arrays.
indicesint[]A 1-D array of sorted integers indicating where along axis 0 the array is split. For example, [2, 3] would result in ary[:2], ary[2:3], ary[3:].
Returns
- NDArray[]
A list of sub-arrays as views into ary.
Remarks
Equivalent to split with axis=0. Array must have ndim >= 2. https://numpy.org/doc/stable/reference/generated/numpy.vsplit.html
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 static NDArray vstack(params NDArray[] tup)
Parameters
tupNDArray[]The arrays must have the same shape along all but the first axis. 1-D arrays must have the same length.
Returns
- NDArray
The array formed by stacking the given arrays, will be at least 2-D.
Remarks
where(NDArray)
Equivalent to nonzero(NDArray): returns the indices where
condition is non-zero.
public static NDArray<long>[] where(NDArray condition)
Parameters
conditionNDArrayInput array. Non-zero entries yield their indices.
Returns
Remarks
where(NDArray, NDArray, NDArray)
Return elements chosen from x or y depending on condition.
public static NDArray where(NDArray condition, NDArray x, NDArray y)
Parameters
conditionNDArrayWhere True, yield
x, otherwise yieldy.xNDArrayValues from which to choose where condition is True.
yNDArrayValues from which to choose where condition is False.
Returns
- NDArray
An array with elements from
xwhereconditionis True, and elements fromyelsewhere.
Remarks
where(NDArray, NDArray, object)
Return elements chosen from x or y depending on condition.
Scalar overload for y.
public static NDArray where(NDArray condition, NDArray x, object y)
Parameters
Returns
where(NDArray, object, NDArray)
Return elements chosen from x or y depending on condition.
Scalar overload for x.
public static NDArray where(NDArray condition, object x, NDArray y)
Parameters
Returns
where(NDArray, object, object)
Return elements chosen from x or y depending on condition.
Scalar overload for both x and y.
public static NDArray where(NDArray condition, object x, object y)
Parameters
Returns
zeros(Shape)
Return a new double array of given shape, filled with zeros.
public static NDArray zeros(Shape shape)
Parameters
shapeShapeShape of the new array,
Returns
- NDArray
Array of zeros with the given shape, dtype.
Remarks
zeros(Shape, DType, string)
Return a new double array of given shape, filled with zeros.
public static NDArray zeros(Shape shape, DType dtype, string device = null)
Parameters
shapeShapeShape of the new array,
dtypeDTypeThe desired dtype for the array — one descriptor parameter, like NumPy's
dtype: a C# Type, an NPTypeCode, a NumPy dtype string ("f4") or a DType (uint8) all convert implicitly. Default (null) is float64 / double.devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity).
Returns
- NDArray
Array of zeros with the given shape, dtype.
Remarks
zeros(Shape, char, DType)
Return a new array of zeros with a specified memory layout — the port of NumPy's
np.zeros(shape, dtype, order='C') order parameter (mirrors empty(Shape, char, DType)).
public static NDArray zeros(Shape shape, char order, DType dtype = null)
Parameters
shapeShapeShape of the new array.
ordercharMemory layout: 'C' (row-major), 'F' (column-major), 'A'/'K' (default to 'C' with no source).
dtypeDTypeDesired dtype (a Type, NPTypeCode, dtype string or DType — all convert implicitly). Default is float64 / double.
Returns
- NDArray
Array of zeros in the requested layout (the fill is order-independent, so only the flags differ).
Remarks
zeros(int)
Return a new double array of given shape, filled with zeros.
public static NDArray zeros(int shape)
Parameters
shapeint
Returns
- NDArray
Array of zeros with the given shape, dtype.
Remarks
zeros(int[])
Return a new double array of given shape, filled with zeros.
public static NDArray zeros(int[] shape)
Parameters
shapeint[]Shape of the new array,
Returns
- NDArray
Array of zeros with the given shape, dtype.
Remarks
zeros(long[])
Return a new double array of given shape, filled with zeros.
public static NDArray zeros(long[] shape)
Parameters
shapelong[]Shape of the new array,
Returns
- NDArray
Array of zeros with the given shape, dtype.
Remarks
zeros_like(NDArray, DType, char, string)
Return an array of zeros with the same shape and type as a given array.
public static NDArray zeros_like(NDArray a, DType dtype, char order, string device = null)
Parameters
aNDArrayThe shape and data-type of a define these same attributes of the returned array.
dtypeDTypeOverrides the data type of the result.
ordercharMemory layout: 'C', 'F', 'A' or 'K' (default, preserves source layout).
devicestringTarget device. Only
"cpu"andnullare accepted (Array-API parity).
Returns
- NDArray
Array of zeros with the same shape and type as
nd.
Remarks
zeros_like(NDArray, DType, string)
Return an array of zeros with the same shape and type as a given array.
public static NDArray zeros_like(NDArray a, DType dtype = null, string device = null)
Parameters
aNDArrayThe shape and data-type of a define these same attributes of the returned array.
dtypeDTypeOverrides the data type of the result.
devicestring
Returns
- NDArray
Array of zeros with the same shape and type as
nd.
Remarks
zeros<T>(int[])
Return a new double array of given shape, filled with zeros.
public static NDArray zeros<T>(int[] shape) where T : unmanaged
Parameters
shapeint[]Shape of the new array,
Returns
- NDArray
Array of zeros with the given shape, type
T.
Type Parameters
T
Remarks
zeros<T>(long[])
Return a new double array of given shape, filled with zeros.
public static NDArray zeros<T>(long[] shape) where T : unmanaged
Parameters
shapelong[]Shape of the new array,
Returns
- NDArray
Array of zeros with the given shape, type
T.
Type Parameters
T