Array API#
Array structure and data access#
These macros access thePyArrayObject
structure members and aredefined inndarraytypes.h
. The input argument,arr, can be anyPyObject* that is directly interpretable as aPyArrayObject* (any instance of thePyArray_Type
and its sub-types).
- intPyArray_NDIM(PyArrayObject*arr)#
The number of dimensions in the array.
- intPyArray_FLAGS(PyArrayObject*arr)#
Returns an integer representing thearray-flags.
- intPyArray_TYPE(PyArrayObject*arr)#
Return the (builtin) typenumber for the elements of this array.
- intPyArray_Pack(constPyArray_Descr*descr,void*item,constPyObject*value)#
New in version 2.0.
Sets the memory location
item
of dtypedescr
tovalue
.The function is equivalent to setting a single array element with a Pythonassignment. Returns 0 on success and -1 with an error set on failure.
Note
If the
descr
has theNPY_NEEDS_INIT
flag set, thedata must be valid or the memory zeroed.
- intPyArray_SETITEM(PyArrayObject*arr,void*itemptr,PyObject*obj)#
Convert obj and place it in the ndarray,arr, at the placepointed to by itemptr. Return -1 if an error occurs or 0 onsuccess.
Note
In general, prefer the use of
PyArray_Pack
whenhandling arbitrary Python objects. Setitem is for example not ableto handle arbitrary casts between different dtypes.
- voidPyArray_ENABLEFLAGS(PyArrayObject*arr,intflags)#
Enables the specified array flags. This function does no validation,and assumes that you know what you’re doing.
- voidPyArray_CLEARFLAGS(PyArrayObject*arr,intflags)#
Clears the specified array flags. This function does no validation,and assumes that you know what you’re doing.
- void*PyArray_DATA(PyArrayObject*arr)#
- char*PyArray_BYTES(PyArrayObject*arr)#
These two macros are similar and obtain the pointer to thedata-buffer for the array. The first macro can (and should be)assigned to a particular pointer where the second is for genericprocessing. If you have not guaranteed a contiguous and/or alignedarray then be sure you understand how to access the data in thearray to avoid memory and/or alignment problems.
- npy_intp*PyArray_DIMS(PyArrayObject*arr)#
Returns a pointer to the dimensions/shape of the array. Thenumber of elements matches the number of dimensionsof the array. Can return
NULL
for 0-dimensional arrays.
- npy_intp*PyArray_SHAPE(PyArrayObject*arr)#
A synonym for
PyArray_DIMS
, named to be consistent with theshape
usage within Python.
- npy_intp*PyArray_STRIDES(PyArrayObject*arr)#
Returns a pointer to the strides of the array. Thenumber of elements matches the number of dimensionsof the array.
- npy_intpPyArray_DIM(PyArrayObject*arr,intn)#
Return the shape in then\(^{\textrm{th}}\) dimension.
- npy_intpPyArray_STRIDE(PyArrayObject*arr,intn)#
Return the stride in then\(^{\textrm{th}}\) dimension.
- npy_intpPyArray_ITEMSIZE(PyArrayObject*arr)#
Return the itemsize for the elements of this array.
Note that, in the old API that was deprecated in version 1.7, this functionhad the return type
int
.
- npy_intpPyArray_SIZE(PyArrayObject*arr)#
Returns the total size (in number of elements) of the array.
- npy_intpPyArray_Size(PyObject*obj)#
Returns 0 ifobj is not a sub-class of ndarray. Otherwise,returns the total number of elements in the array. Safer versionof
PyArray_SIZE
(obj).
- npy_intpPyArray_NBYTES(PyArrayObject*arr)#
Returns the total number of bytes consumed by the array.
- PyObject*PyArray_BASE(PyArrayObject*arr)#
This returns the base object of the array. In most cases, thismeans the object which owns the memory the array is pointing at.
If you are constructing an array using the C API, and specifyingyour own memory, you should use the function
PyArray_SetBaseObject
to set the base to an object which owns the memory.If the
NPY_ARRAY_WRITEBACKIFCOPY
flag is set, it has a differentmeaning, namely base is the array into which the current array willbe copied upon copy resolution. This overloading of the base propertyfor two functions is likely to change in a future version of NumPy.
- PyArray_Descr*PyArray_DESCR(PyArrayObject*arr)#
Returns a borrowed reference to the dtype property of the array.
- PyArray_Descr*PyArray_DTYPE(PyArrayObject*arr)#
A synonym for PyArray_DESCR, named to be consistent with the‘dtype’ usage within Python.
- PyObject*PyArray_GETITEM(PyArrayObject*arr,void*itemptr)#
Get a Python object of a builtin type from the ndarray,arr,at the location pointed to by itemptr. Return
NULL
on failure.numpy.ndarray.item
is identical to PyArray_GETITEM.
- intPyArray_FinalizeFunc(PyArrayObject*arr,PyObject*obj)#
The function pointed to by the
PyCapsule
__array_finalize__
.The first argument is the newly created sub-type. The second argument(if not NULL) is the “parent” array (if the array was created usingslicing or some other operation where a clearly-distinguishable parentis present). This routine can do anything it wants to. It shouldreturn a -1 on error and 0 otherwise.
Data access#
These functions and macros provide easy access to elements of thendarray from C. These work for all arrays. You may need to take carewhen accessing the data in the array, however, if it is not in machinebyte-order, misaligned, or not writeable. In other words, be sure torespect the state of the flags unless you know what you are doing, orhave previously guaranteed an array that is writeable, aligned, and inmachine byte-order usingPyArray_FromAny
. If you wish to handle alltypes of arrays, the copyswap function for each type is useful forhandling misbehaved arrays. Some platforms (e.g. Solaris) do not likemisaligned data and will crash if you de-reference a misalignedpointer. Other platforms (e.g. x86 Linux) will just work more slowlywith misaligned data.
- void*PyArray_GetPtr(PyArrayObject*aobj,npy_intp*ind)#
Return a pointer to the data of the ndarray,aobj, at theN-dimensional index given by the c-array,ind, (which must beat leastaobj ->nd in size). You may want to typecast thereturned pointer to the data type of the ndarray.
- void*PyArray_GETPTR1(PyArrayObject*obj,npy_intpi)#
- void*PyArray_GETPTR2(PyArrayObject*obj,npy_intpi,npy_intpj)#
- void*PyArray_GETPTR3(PyArrayObject*obj,npy_intpi,npy_intpj,npy_intpk)#
- void*PyArray_GETPTR4(PyArrayObject*obj,npy_intpi,npy_intpj,npy_intpk,npy_intpl)#
Quick, inline access to the element at the given coordinates inthe ndarray,obj, which must have respectively 1, 2, 3, or 4dimensions (this is not checked). The correspondingi,j,k, andl coordinates can be any integer but will beinterpreted as
npy_intp
. You may want to typecast thereturned pointer to the data type of the ndarray.
Creating arrays#
From scratch#
- PyObject*PyArray_NewFromDescr(PyTypeObject*subtype,PyArray_Descr*descr,intnd,npy_intpconst*dims,npy_intpconst*strides,void*data,intflags,PyObject*obj)#
This function steals a reference todescr. The easiest way to get oneis using
PyArray_DescrFromType
.This is the main array creation function. Most new arrays arecreated with this flexible function.
The returned object is an object of Python-typesubtype, whichmust be a subtype of
PyArray_Type
. The array hasnddimensions, described bydims. The data-type descriptor of thenew array isdescr.Ifsubtype is of an array subclass instead of the base
&PyArray_Type
, thenobj is the object to pass tothe__array_finalize__
method of the subclass.Ifdata is
NULL
, then new unitinialized memory will be allocated andflags can be non-zero to indicate a Fortran-style contiguous array. UsePyArray_FILLWBYTE
to initialize the memory.Ifdata is not
NULL
, then it is assumed to point to the memoryto be used for the array and theflags argument is used as thenew flags for the array (except the state ofNPY_ARRAY_OWNDATA
,NPY_ARRAY_WRITEBACKIFCOPY
flag of the new array will be reset).In addition, ifdata is non-NULL, thenstrides canalso be provided. Ifstrides is
NULL
, then the array stridesare computed as C-style contiguous (default) or Fortran-stylecontiguous (flags is nonzero fordata =NULL
orflags &NPY_ARRAY_F_CONTIGUOUS
is nonzero non-NULLdata). Anyprovideddims andstrides are copied into newly allocateddimension and strides arrays for the new array object.PyArray_CheckStrides
can help verify non-NULL
strideinformation.If
data
is provided, it must stay alive for the life of the array. Oneway to manage this is throughPyArray_SetBaseObject
- PyObject*PyArray_NewLikeArray(PyArrayObject*prototype,NPY_ORDERorder,PyArray_Descr*descr,intsubok)#
This function steals a reference todescr if it is not NULL.This array creation routine allows for the convenient creation ofa new array matching an existing array’s shapes and memory layout,possibly changing the layout and/or data type.
Whenorder is
NPY_ANYORDER
, the result order isNPY_FORTRANORDER
ifprototype is a fortran array,NPY_CORDER
otherwise. Whenorder isNPY_KEEPORDER
, the result order matches that ofprototype, evenwhen the axes ofprototype aren’t in C or Fortran order.Ifdescr is NULL, the data type ofprototype is used.
Ifsubok is 1, the newly created array will use the sub-type ofprototype to create the new array, otherwise it will create abase-class array.
- PyObject*PyArray_New(PyTypeObject*subtype,intnd,npy_intpconst*dims,inttype_num,npy_intpconst*strides,void*data,intitemsize,intflags,PyObject*obj)#
This is similar to
PyArray_NewFromDescr
(…) except youspecify the data-type descriptor withtype_num anditemsize,wheretype_num corresponds to a builtin (or user-defined)type. If the type always has the same number of bytes, thenitemsize is ignored. Otherwise, itemsize specifies the particularsize of this array.
Warning
If data is passed toPyArray_NewFromDescr
orPyArray_New
,this memory must not be deallocated until the new array isdeleted. If this data came from another Python object, this canbe accomplished usingPy_INCREF
on that object and setting thebase member of the new array to point to that object. If stridesare passed in they must be consistent with the dimensions, theitemsize, and the data of the array.
- PyObject*PyArray_SimpleNew(intnd,npy_intpconst*dims,inttypenum)#
Create a new uninitialized array of type,typenum, whose size ineach ofnd dimensions is given by the integer array,dims.The memoryfor the array is uninitialized (unless typenum is
NPY_OBJECT
in which case each element in the array is set to NULL). Thetypenum argument allows specification of any of the builtindata-types such asNPY_FLOAT
orNPY_LONG
. Thememory for the array can be set to zero if desired usingPyArray_FILLWBYTE
(return_object, 0).This function cannot beused to create a flexible-type array (no itemsize given).
- PyObject*PyArray_SimpleNewFromData(intnd,npy_intpconst*dims,inttypenum,void*data)#
Create an array wrapper arounddata pointed to by the givenpointer. The array flags will have a default that the data area iswell-behaved and C-style contiguous. The shape of the array isgiven by thedims c-array of lengthnd. The data-type of thearray is indicated bytypenum. If data comes from anotherreference-counted Python object, the reference count on this objectshould be increased after the pointer is passed in, and the base memberof the returned ndarray should point to the Python object that ownsthe data. This will ensure that the provided memory is notfreed while the returned array is in existence.
- PyObject*PyArray_SimpleNewFromDescr(intnd,npy_intconst*dims,PyArray_Descr*descr)#
This function steals a reference todescr.
Create a new array with the provided data-type descriptor,descr,of the shape determined bynd anddims.
- voidPyArray_FILLWBYTE(PyObject*obj,intval)#
Fill the array pointed to byobj —which must be a (subclassof) ndarray—with the contents ofval (evaluated as a byte).This macro calls memset, so obj must be contiguous.
- PyObject*PyArray_Zeros(intnd,npy_intpconst*dims,PyArray_Descr*dtype,intfortran)#
Construct a newnd -dimensional array with shape given bydimsand data type given bydtype. Iffortran is non-zero, then aFortran-order array is created, otherwise a C-order array iscreated. Fill the memory with zeros (or the 0 object ifdtypecorresponds to
NPY_OBJECT
).
- PyObject*PyArray_ZEROS(intnd,npy_intpconst*dims,inttype_num,intfortran)#
Macro form of
PyArray_Zeros
which takes a type-number insteadof a data-type object.
- PyObject*PyArray_Empty(intnd,npy_intpconst*dims,PyArray_Descr*dtype,intfortran)#
Construct a newnd -dimensional array with shape given bydimsand data type given bydtype. Iffortran is non-zero, then aFortran-order array is created, otherwise a C-order array iscreated. The array is uninitialized unless the data typecorresponds to
NPY_OBJECT
in which case the array isfilled withPy_None
.
- PyObject*PyArray_EMPTY(intnd,npy_intpconst*dims,inttypenum,intfortran)#
Macro form of
PyArray_Empty
which takes a type-number,typenum, instead of a data-type object.
- PyObject*PyArray_Arange(doublestart,doublestop,doublestep,inttypenum)#
Construct a new 1-dimensional array of data-type,typenum, thatranges fromstart tostop (exclusive) in increments ofstep. Equivalent toarange (start,stop,step, dtype).
- PyObject*PyArray_ArangeObj(PyObject*start,PyObject*stop,PyObject*step,PyArray_Descr*descr)#
Construct a new 1-dimensional array of data-type determined by
descr
, that ranges fromstart
tostop
(exclusive) inincrements ofstep
. Equivalent to arange(start
,stop
,step
,typenum
).
- intPyArray_SetBaseObject(PyArrayObject*arr,PyObject*obj)#
This functionsteals a reference to
obj
and sets it as thebase property ofarr
.If you construct an array by passing in your own memory buffer asa parameter, you need to set the array’sbase property to ensurethe lifetime of the memory buffer is appropriate.
The return value is 0 on success, -1 on failure.
If the object provided is an array, this function traverses thechain ofbase pointers so that each array points to the ownerof the memory directly. Once the base is set, it may not be changedto another value.
From other objects#
- PyObject*PyArray_FromAny(PyObject*op,PyArray_Descr*dtype,intmin_depth,intmax_depth,intrequirements,PyObject*context)#
This is the main function used to obtain an array from any nestedsequence, or object that exposes the array interface,op. Theparameters allow specification of the requireddtype, theminimum (min_depth) and maximum (max_depth) number ofdimensions acceptable, and otherrequirements for the array. Thisfunctionsteals a reference to the dtype argument, which needsto be a
PyArray_Descr
structureindicating the desired data-type (including requiredbyteorder). Thedtype argument may beNULL
, indicating that anydata-type (and byteorder) is acceptable. UnlessNPY_ARRAY_FORCECAST
is present inflags
,this call will generate an error if the datatype cannot be safely obtained from the object. If you want to useNULL
for thedtype and ensure the array is not swapped thenusePyArray_CheckFromAny
. A value of 0 for either of thedepth parameters causes the parameter to be ignored. Any of thefollowing array flags can be added (e.g. using |) to get therequirements argument. If your code can handle general (e.g.strided, byte-swapped, or unaligned arrays) thenrequirementsmay be 0. Also, ifop is not already an array (or does notexpose the array interface), then a new array will be created (andfilled fromop using the sequence protocol). The new array willhaveNPY_ARRAY_DEFAULT
as its flags member. Thecontextargument is unused.NPY_ARRAY_C_CONTIGUOUS
Make sure the returned array is C-style contiguous
NPY_ARRAY_F_CONTIGUOUS
Make sure the returned array is Fortran-style contiguous.
NPY_ARRAY_ALIGNED
Make sure the returned array is aligned on proper boundaries for itsdata type. An aligned array has the data pointer and every stridesfactor as a multiple of the alignment factor for the data-type-descriptor.
NPY_ARRAY_WRITEABLE
Make sure the returned array can be written to.
NPY_ARRAY_ENSURECOPY
Make sure a copy is made ofop. If this flag is notpresent, data is not copied if it can be avoided.
NPY_ARRAY_ENSUREARRAY
Make sure the result is a base-class ndarray. Bydefault, ifop is an instance of a subclass ofndarray, an instance of that same subclass is returned. Ifthis flag is set, an ndarray object will be returned instead.
NPY_ARRAY_FORCECAST
Force a cast to the output type even if it cannot be donesafely. Without this flag, a data cast will occur only if itcan be done safely, otherwise an error is raised.
NPY_ARRAY_WRITEBACKIFCOPY
Ifop is already an array, but does not satisfy therequirements, then a copy is made (which will satisfy therequirements). If this flag is present and a copy (of an objectthat is already an array) must be made, then the corresponding
NPY_ARRAY_WRITEBACKIFCOPY
flag is set in the returnedcopy andop is made to be read-only. You must be sure to callPyArray_ResolveWritebackIfCopy
to copy the contentsback intoop and theop arraywill be made writeable again. Ifop is not writeable to beginwith, or if it is not already an array, then an error is raised.
Combinations of array flags can also be added.
- PyObject*PyArray_CheckFromAny(PyObject*op,PyArray_Descr*dtype,intmin_depth,intmax_depth,intrequirements,PyObject*context)#
Nearly identical to
PyArray_FromAny
(…) exceptrequirements can containNPY_ARRAY_NOTSWAPPED
(over-riding thespecification indtype) andNPY_ARRAY_ELEMENTSTRIDES
whichindicates that the array should be aligned in the sense that thestrides are multiples of the element size.
- PyObject*PyArray_FromArray(PyArrayObject*op,PyArray_Descr*newtype,intrequirements)#
Special case of
PyArray_FromAny
for whenop is already anarray but it needs to be of a specificnewtype (includingbyte-order) or has certainrequirements.
- PyObject*PyArray_FromStructInterface(PyObject*op)#
Returns an ndarray object from a Python object that exposes the
__array_struct__
attribute and follows the array interfaceprotocol. If the object does not contain this attribute then aborrowed reference toPy_NotImplemented
is returned.
- PyObject*PyArray_FromInterface(PyObject*op)#
Returns an ndarray object from a Python object that exposes the
__array_interface__
attribute following the array interfaceprotocol. If the object does not contain this attribute then aborrowed reference toPy_NotImplemented
is returned.
- PyObject*PyArray_FromArrayAttr(PyObject*op,PyArray_Descr*dtype,PyObject*context)#
Return an ndarray object from a Python object that exposes the
__array__
method. The third-party implementations of__array__
must takedtype
andcopy
keywordarguments.context
is unused.
- PyObject*PyArray_ContiguousFromAny(PyObject*op,inttypenum,intmin_depth,intmax_depth)#
This function returns a (C-style) contiguous and behaved functionarray from any nested sequence or array interface exportingobject,op, of (non-flexible) type given by the enumeratedtypenum, of minimum depthmin_depth, and of maximum depthmax_depth. Equivalent to a call to
PyArray_FromAny
withrequirements set toNPY_ARRAY_DEFAULT
and the type_num member of thetype argument set totypenum.
- PyObject*PyArray_ContiguousFromObject(PyObject*op,inttypenum,intmin_depth,intmax_depth)#
This function returns a well-behaved C-style contiguous array from any nestedsequence or array-interface exporting object. The minimum number of dimensionsthe array can have is given bymin_depth while the maximum ismax_depth.This is equivalent to call
PyArray_FromAny
with requirementsNPY_ARRAY_DEFAULT
andNPY_ARRAY_ENSUREARRAY
.
- PyObject*PyArray_FromObject(PyObject*op,inttypenum,intmin_depth,intmax_depth)#
Return an aligned and in native-byteorder array from any nestedsequence or array-interface exporting object, op, of a type given bythe enumerated typenum. The minimum number of dimensions the array canhave is given by min_depth while the maximum is max_depth. This isequivalent to a call to
PyArray_FromAny
with requirements set toBEHAVED.
- PyObject*PyArray_EnsureArray(PyObject*op)#
This functionsteals a reference to
op
and makes sure thatop
is a base-class ndarray. It special cases array scalars,but otherwise callsPyArray_FromAny
(op
, NULL, 0, 0,NPY_ARRAY_ENSUREARRAY
, NULL).
- PyObject*PyArray_FromString(char*string,npy_intpslen,PyArray_Descr*dtype,npy_intpnum,char*sep)#
Construct a one-dimensional ndarray of a single type from a binaryor (ASCII) text
string
of lengthslen
. The data-type ofthe array to-be-created is given bydtype
. If num is -1, thencopy the entire string and return an appropriately sizedarray, otherwise,num
is the number of items tocopy fromthe string. Ifsep
is NULL (or “”), then interpret the stringas bytes of binary data, otherwise convert the sub-stringsseparated bysep
to items of data-typedtype
. Somedata-types may not be readable in text mode and an error will beraised if that occurs. All errors return NULL.
- PyObject*PyArray_FromFile(FILE*fp,PyArray_Descr*dtype,npy_intpnum,char*sep)#
Construct a one-dimensional ndarray of a single type from a binaryor text file. The open file pointer is
fp
, the data-type ofthe array to be created is given bydtype
. This must matchthe data in the file. Ifnum
is -1, then read until the end ofthe file and return an appropriately sized array, otherwise,num
is the number of items to read. Ifsep
is NULL (or“”), then read from the file in binary mode, otherwise read fromthe file in text mode withsep
providing the itemseparator. Some array types cannot be read in text mode in whichcase an error is raised.
- PyObject*PyArray_FromBuffer(PyObject*buf,PyArray_Descr*dtype,npy_intpcount,npy_intpoffset)#
Construct a one-dimensional ndarray of a single type from anobject,
buf
, that exports the (single-segment) buffer protocol(or has an attribute __buffer__ that returns an object thatexports the buffer protocol). A writeable buffer will be triedfirst followed by a read- only buffer. TheNPY_ARRAY_WRITEABLE
flag of the returned array will reflect which one wassuccessful. The data is assumed to start atoffset
bytes fromthe start of the memory location for the object. The type of thedata in the buffer will be interpreted depending on the data- typedescriptor,dtype.
Ifcount
is negative then it will bedetermined from the size of the buffer and the requested itemsize,otherwise,count
represents how many elements should beconverted from the buffer.
- intPyArray_CopyInto(PyArrayObject*dest,PyArrayObject*src)#
Copy from the source array,
src
, into the destination array,dest
, performing a data-type conversion if necessary. If anerror occurs return -1 (otherwise 0). The shape ofsrc
must bebroadcastable to the shape ofdest
.NumPy checks for overlapping memory when copying two arrays.
- intPyArray_CopyObject(PyArrayObject*dest,PyObject*src)#
Assign an object
src
to a NumPy arraydest
according toarray-coercion rules. This is basically identical toPyArray_FromAny
, but assigns directly to the output array.Returns 0 on success and -1 on failures.
- PyArrayObject*PyArray_GETCONTIGUOUS(PyObject*op)#
If
op
is already (C-style) contiguous and well-behaved thenjust return a reference, otherwise return a (contiguous andwell-behaved) copy of the array. The parameter op must be a(sub-class of an) ndarray and no checking for that is done.
- PyObject*PyArray_FROM_O(PyObject*obj)#
Convert
obj
to an ndarray. The argument can be any nestedsequence or object that exports the array interface. This is amacro form ofPyArray_FromAny
usingNULL
, 0, 0, 0 for theother arguments. Your code must be able to handle any data-typedescriptor and any combination of data-flags to use this macro.
- PyObject*PyArray_FROM_OF(PyObject*obj,intrequirements)#
Similar to
PyArray_FROM_O
except it can take an argumentofrequirements indicating properties the resulting array musthave. Available requirements that can be enforced areNPY_ARRAY_C_CONTIGUOUS
,NPY_ARRAY_F_CONTIGUOUS
,NPY_ARRAY_ALIGNED
,NPY_ARRAY_WRITEABLE
,NPY_ARRAY_NOTSWAPPED
,NPY_ARRAY_ENSURECOPY
,NPY_ARRAY_WRITEBACKIFCOPY
,NPY_ARRAY_FORCECAST
, andNPY_ARRAY_ENSUREARRAY
. Standard combinations of flags can alsobe used:
- PyObject*PyArray_FROM_OT(PyObject*obj,inttypenum)#
Similar to
PyArray_FROM_O
except it can take an argument oftypenum specifying the type-number the returned array.
- PyObject*PyArray_FROM_OTF(PyObject*obj,inttypenum,intrequirements)#
Combination of
PyArray_FROM_OF
andPyArray_FROM_OT
allowing both atypenum and aflags argument to be provided.
- PyObject*PyArray_FROMANY(PyObject*obj,inttypenum,intmin,intmax,intrequirements)#
Similar to
PyArray_FromAny
except the data-type isspecified using a typenumber.PyArray_DescrFromType
(typenum) is passed directly toPyArray_FromAny
. Thismacro also addsNPY_ARRAY_DEFAULT
to requirements ifNPY_ARRAY_ENSURECOPY
is passed in as requirements.
- PyObject*PyArray_CheckAxis(PyObject*obj,int*axis,intrequirements)#
Encapsulate the functionality of functions and methods that takethe axis= keyword and work properly with None as the axisargument. The input array is
obj
, while*axis
is aconverted integer (so that*axis==NPY_RAVEL_AXIS
is the None value), andrequirements
gives the needed properties ofobj
. Theoutput is a converted version of the input so that requirementsare met and if needed a flattening has occurred. On outputnegative values of*axis
are converted and the new value ischecked to ensure consistency with the shape ofobj
.
Dealing with types#
General check of Python Type#
- intPyArray_Check(PyObject*op)#
Evaluates true ifop is a Python object whose type is a sub-typeof
PyArray_Type
.
- intPyArray_CheckExact(PyObject*op)#
Evaluates true ifop is a Python object with type
PyArray_Type
.
- intPyArray_HasArrayInterface(PyObject*op,PyObject*out)#
If
op
implements any part of the array interface, thenout
will contain a new reference to the newly created ndarray usingthe interface orout
will containNULL
if an error duringconversion occurs. Otherwise, out will contain a borrowedreference toPy_NotImplemented
and no error condition is set.
- intPyArray_HasArrayInterfaceType(PyObject*op,PyArray_Descr*dtype,PyObject*context,PyObject*out)#
If
op
implements any part of the array interface, thenout
will contain a new reference to the newly created ndarray usingthe interface orout
will containNULL
if an error duringconversion occurs. Otherwise, out will contain a borrowedreference to Py_NotImplemented and no error condition is set.This version allows setting of the dtype in the part of the array interfacethat looks for the__array__
attribute.context isunused.
- intPyArray_IsZeroDim(PyObject*op)#
Evaluates true ifop is an instance of (a subclass of)
PyArray_Type
and has 0 dimensions.
- PyArray_IsScalar(op,cls)#
Evaluates true ifop is an instance of
Py{cls}ArrType_Type
.
- intPyArray_CheckScalar(PyObject*op)#
Evaluates true ifop is either an array scalar (an instance of asub-type of
PyGenericArrType_Type
), or an instance of (asub-class of)PyArray_Type
whose dimensionality is 0.
- intPyArray_IsPythonNumber(PyObject*op)#
Evaluates true ifop is an instance of a builtin numeric type (int,float, complex, long, bool)
- intPyArray_IsPythonScalar(PyObject*op)#
Evaluates true ifop is a builtin Python scalar object (int,float, complex, bytes, str, long, bool).
- intPyArray_IsAnyScalar(PyObject*op)#
Evaluates true ifop is either a Python scalar object (see
PyArray_IsPythonScalar
) or an array scalar (an instance of a sub-type ofPyGenericArrType_Type
).
- intPyArray_CheckAnyScalar(PyObject*op)#
Evaluates true ifop is a Python scalar object (see
PyArray_IsPythonScalar
), an array scalar (an instance of asub-type ofPyGenericArrType_Type
) or an instance of a sub-type ofPyArray_Type
whose dimensionality is 0.
Data-type accessors#
Some of the descriptor attributes may not always be defined and should orcannot not be accessed directly.
Changed in version 2.0:Prior to NumPy 2.0 the ABI was different but unnecessary large for userDTypes. These accessors were all added in 2.0 and can be backported(seeThe PyArray_Descr struct has been changed).
- npy_intpPyDataType_ELSIZE(PyArray_Descr*descr)#
The element size of the datatype (
itemsize
in Python).Note
If the
descr
is attached to an arrayPyArray_ITEMSIZE(arr)
can be used and is available on all NumPy versions.
- voidPyDataType_SET_ELSIZE(PyArray_Descr*descr,npy_intpsize)#
Allows setting of the itemsize, this isonly relevant for string/bytesdatatypes as it is the current pattern to define one with a new size.
- npy_intpPyDataType_ALIGNENT(PyArray_Descr*descr)#
The alignment of the datatype.
- PyObject*PyDataType_METADATA(PyArray_Descr*descr)#
The Metadata attached to a dtype, either
NULL
or a dictionary.
- PyObject*PyDataType_NAMES(PyArray_Descr*descr)#
NULL
or a tuple of structured field names attached to a dtype.
- PyObject*PyDataType_FIELDS(PyArray_Descr*descr)#
NULL
,None
, or a dict of structured dtype fields, this dict mustnot be mutated, NumPy may change the way fields are stored in the future.This is the same dict as returned bynp.dtype.fields.
- NpyAuxData*PyDataType_C_METADATA(PyArray_Descr*descr)#
C-metadata object attached to a descriptor. This accessor should notbe needed usually. The C-Metadata field does provide access to thedatetime/timedelta time unit information.
- PyArray_ArrayDescr*PyDataType_SUBARRAY(PyArray_Descr*descr)#
Information about a subarray dtype equivalent to the Pythonnp.dtype.baseandnp.dtype.shape.
If this is non-
NULL
, then this data-type descriptor is aC-style contiguous array of another data-type descriptor. Inother-words, each element that this descriptor describes isactually an array of some other base descriptor. This is mostuseful as the data-type descriptor for a field in anotherdata-type descriptor. The fields member should beNULL
if thisis non-NULL
(the fields member of the base descriptor can benon-NULL
however).- typePyArray_ArrayDescr#
typedefstruct{PyArray_Descr*base;PyObject*shape;}PyArray_ArrayDescr;
- PyArray_Descr*base#
The data-type-descriptor object of the base-type.
- PyArray_Descr*base#
- typePyArray_ArrayDescr#
Data-type checking#
For the typenum macros, the argument is an integer representing anenumerated array data type. For the array type checking macros theargument must be aPyObject* that can be directly interpreted as aPyArrayObject*.
- intPyTypeNum_ISUNSIGNED(intnum)#
- intPyDataType_ISUNSIGNED(PyArray_Descr*descr)#
- intPyArray_ISUNSIGNED(PyArrayObject*obj)#
Type represents an unsigned integer.
- intPyTypeNum_ISSIGNED(intnum)#
- intPyDataType_ISSIGNED(PyArray_Descr*descr)#
- intPyArray_ISSIGNED(PyArrayObject*obj)#
Type represents a signed integer.
- intPyTypeNum_ISINTEGER(intnum)#
- intPyDataType_ISINTEGER(PyArray_Descr*descr)#
- intPyArray_ISINTEGER(PyArrayObject*obj)#
Type represents any integer.
- intPyTypeNum_ISFLOAT(intnum)#
- intPyDataType_ISFLOAT(PyArray_Descr*descr)#
- intPyArray_ISFLOAT(PyArrayObject*obj)#
Type represents any floating point number.
- intPyTypeNum_ISCOMPLEX(intnum)#
- intPyDataType_ISCOMPLEX(PyArray_Descr*descr)#
- intPyArray_ISCOMPLEX(PyArrayObject*obj)#
Type represents any complex floating point number.
- intPyTypeNum_ISNUMBER(intnum)#
- intPyDataType_ISNUMBER(PyArray_Descr*descr)#
- intPyArray_ISNUMBER(PyArrayObject*obj)#
Type represents any integer, floating point, or complex floating pointnumber.
- intPyTypeNum_ISSTRING(intnum)#
- intPyDataType_ISSTRING(PyArray_Descr*descr)#
- intPyArray_ISSTRING(PyArrayObject*obj)#
Type represents a string data type.
- intPyTypeNum_ISFLEXIBLE(intnum)#
- intPyDataType_ISFLEXIBLE(PyArray_Descr*descr)#
- intPyArray_ISFLEXIBLE(PyArrayObject*obj)#
Type represents one of the flexible array types (
NPY_STRING
,NPY_UNICODE
, orNPY_VOID
).
- intPyDataType_ISUNSIZED(PyArray_Descr*descr)#
Type has no size information attached, and can be resized. Should only becalled on flexible dtypes. Types that are attached to an array will alwaysbe sized, hence the array form of this macro not existing.
For structured datatypes with no fields this function now returns False.
- intPyTypeNum_ISUSERDEF(intnum)#
- intPyDataType_ISUSERDEF(PyArray_Descr*descr)#
- intPyArray_ISUSERDEF(PyArrayObject*obj)#
Type represents a user-defined type.
- intPyTypeNum_ISEXTENDED(intnum)#
- intPyDataType_ISEXTENDED(PyArray_Descr*descr)#
- intPyArray_ISEXTENDED(PyArrayObject*obj)#
Type is either flexible or user-defined.
- intPyTypeNum_ISOBJECT(intnum)#
- intPyDataType_ISOBJECT(PyArray_Descr*descr)#
- intPyArray_ISOBJECT(PyArrayObject*obj)#
Type represents object data type.
- intPyTypeNum_ISBOOL(intnum)#
- intPyDataType_ISBOOL(PyArray_Descr*descr)#
- intPyArray_ISBOOL(PyArrayObject*obj)#
Type represents Boolean data type.
- intPyDataType_HASFIELDS(PyArray_Descr*descr)#
- intPyArray_HASFIELDS(PyArrayObject*obj)#
Type has fields associated with it.
- intPyArray_ISNOTSWAPPED(PyArrayObject*m)#
Evaluates true if the data area of the ndarraym is in machinebyte-order according to the array’s data-type descriptor.
- intPyArray_ISBYTESWAPPED(PyArrayObject*m)#
Evaluates true if the data area of the ndarraym isnot inmachine byte-order according to the array’s data-type descriptor.
- npy_boolPyArray_EquivTypes(PyArray_Descr*type1,PyArray_Descr*type2)#
Return
NPY_TRUE
iftype1 andtype2 actually representequivalent types for this platform (the fortran member of eachtype is ignored). For example, on 32-bit platforms,NPY_LONG
andNPY_INT
are equivalent. OtherwisereturnNPY_FALSE
.
- npy_boolPyArray_EquivArrTypes(PyArrayObject*a1,PyArrayObject*a2)#
Return
NPY_TRUE
ifa1 anda2 are arrays with equivalenttypes for this platform.
- npy_boolPyArray_EquivTypenums(inttypenum1,inttypenum2)#
Special case of
PyArray_EquivTypes
(…) that does not acceptflexible data types but may be easier to call.
- intPyArray_EquivByteorders(intb1,intb2)#
True if byteorder charactersb1 andb2 (
NPY_LITTLE
,NPY_BIG
,NPY_NATIVE
,NPY_IGNORE
) areeither equal or equivalent as to their specification of a nativebyte order. Thus, on a little-endian machineNPY_LITTLE
andNPY_NATIVE
are equivalent where they are notequivalent on a big-endian machine.
Converting data types#
- PyObject*PyArray_Cast(PyArrayObject*arr,inttypenum)#
Mainly for backwards compatibility to the Numeric C-API and forsimple casts to non-flexible types. Return a new array object withthe elements ofarr cast to the data-typetypenum which mustbe one of the enumerated types and not a flexible type.
- PyObject*PyArray_CastToType(PyArrayObject*arr,PyArray_Descr*type,intfortran)#
Return a new array of thetype specified, casting the elementsofarr as appropriate. The fortran argument specifies theordering of the output array.
- intPyArray_CastTo(PyArrayObject*out,PyArrayObject*in)#
As of 1.6, this function simply calls
PyArray_CopyInto
,which handles the casting.Cast the elements of the arrayin into the arrayout. Theoutput array should be writeable, have an integer-multiple of thenumber of elements in the input array (more than one copy can beplaced in out), and have a data type that is one of the builtintypes. Returns 0 on success and -1 if an error occurs.
- intPyArray_CanCastSafely(intfromtype,inttotype)#
Returns non-zero if an array of data typefromtype can be castto an array of data typetotype without losing information. Anexception is that 64-bit integers are allowed to be cast to 64-bitfloating point values even though this can lose precision on largeintegers so as not to proliferate the use of long doubles withoutexplicit requests. Flexible array types are not checked accordingto their lengths with this function.
- intPyArray_CanCastTo(PyArray_Descr*fromtype,PyArray_Descr*totype)#
PyArray_CanCastTypeTo
supersedes this function inNumPy 1.6 and later.Equivalent to PyArray_CanCastTypeTo(fromtype, totype, NPY_SAFE_CASTING).
- intPyArray_CanCastTypeTo(PyArray_Descr*fromtype,PyArray_Descr*totype,NPY_CASTINGcasting)#
Returns non-zero if an array of data typefromtype (which caninclude flexible types) can be cast safely to an array of datatypetotype (which can include flexible types) according tothe casting rulecasting. For simple types with
NPY_SAFE_CASTING
,this is basically a wrapper aroundPyArray_CanCastSafely
, butfor flexible types such as strings or unicode, it produces resultstaking into account their sizes. Integer and float types can only be castto a string or unicode type usingNPY_SAFE_CASTING
if the stringor unicode type is big enough to hold the max value of the integer/floattype being cast from.
- intPyArray_CanCastArrayTo(PyArrayObject*arr,PyArray_Descr*totype,NPY_CASTINGcasting)#
Returns non-zero ifarr can be cast tototype accordingto the casting rule given incasting. Ifarr is an arrayscalar, its value is taken into account, and non-zero is alsoreturned when the value will not overflow or be truncated toan integer when converting to a smaller type.
- PyArray_Descr*PyArray_MinScalarType(PyArrayObject*arr)#
Note
With the adoption of NEP 50 in NumPy 2, this function is not usedinternally. It is currently provided for backwards compatibility,but expected to be eventually deprecated.
Ifarr is an array, returns its data type descriptor, but ifarr is an array scalar (has 0 dimensions), it finds the data typeof smallest size to which the value may be convertedwithout overflow or truncation to an integer.
This function will not demote complex to float or anything toboolean, but will demote a signed integer to an unsigned integerwhen the scalar value is positive.
- PyArray_Descr*PyArray_PromoteTypes(PyArray_Descr*type1,PyArray_Descr*type2)#
Finds the data type of smallest size and kind to whichtype1 andtype2 may be safely converted. This function is symmetric andassociative. A string or unicode result will be the proper size forstoring the max value of the input types converted to a string or unicode.
- PyArray_Descr*PyArray_ResultType(npy_intpnarrs,PyArrayObject**arrs,npy_intpndtypes,PyArray_Descr**dtypes)#
This applies type promotion to all the input arrays and dtypeobjects, using the NumPy rules for combining scalars and arrays, todetermine the output type for an operation with the given set ofoperands. This is the same result type that ufuncs produce.
See the documentation of
numpy.result_type
for moredetail about the type promotion algorithm.
- intPyArray_ObjectType(PyObject*op,intmintype)#
This function is superseded by
PyArray_ResultType
.This function is useful for determining a common type that two ormore arrays can be converted to. It only works for non-flexiblearray types as no itemsize information is passed. Themintypeargument represents the minimum type acceptable, andoprepresents the object that will be converted to an array. Thereturn value is the enumerated typenumber that represents thedata-type thatop should have.
- PyArrayObject**PyArray_ConvertToCommonType(PyObject*op,int*n)#
The functionality this provides is largely superseded by iterator
NpyIter
introduced in 1.6, with flagNPY_ITER_COMMON_DTYPE
or with the same dtype parameter forall operands.Convert a sequence of Python objects contained inop to an arrayof ndarrays each having the same data type. The type is selectedin the same way as
PyArray_ResultType
. The length of the sequence isreturned inn, and ann -length array ofPyArrayObject
pointers is the return value (orNULL
if an error occurs).The returned array must be freed by the caller of this routine(usingPyDataMem_FREE
) and all the array objects in itDECREF
‘d or a memory-leak will occur. The example template-codebelow shows a typical usage:mps=PyArray_ConvertToCommonType(obj,&n);if(mps==NULL)returnNULL;{code}<beforereturn>for(i=0;i<n;i++)Py_DECREF(mps[i]);PyDataMem_FREE(mps);{return}
- char*PyArray_Zero(PyArrayObject*arr)#
A pointer to newly created memory of sizearr ->itemsize thatholds the representation of 0 for that type. The returned pointer,ret,must be freed using
PyDataMem_FREE
(ret) when it isnot needed anymore.
- char*PyArray_One(PyArrayObject*arr)#
A pointer to newly created memory of sizearr ->itemsize thatholds the representation of 1 for that type. The returned pointer,ret,must be freed using
PyDataMem_FREE
(ret) when itis not needed anymore.
User-defined data types#
- voidPyArray_InitArrFuncs(PyArray_ArrFuncs*f)#
Initialize all function pointers and members to
NULL
.
- intPyArray_RegisterDataType(PyArray_DescrProto*dtype)#
Note
As of NumPy 2.0 this API is considered legacy, the new DType APIis more powerful and provides additional flexibility.The API may eventually be deprecated but support is continued forthe time being.
Compiling for NumPy 1.x and 2.x
NumPy 2.x requires passing in a
PyArray_DescrProto
typed structrather than aPyArray_Descr
. This is necessary to allow changes.To allow code to run and compile on both 1.x and 2.x you need tochange the type of your struct toPyArray_DescrProto
and add:/*AllowcompilingonNumPy1.x*/#if NPY_ABI_VERSION < 0x02000000#define PyArray_DescrProto PyArray_Descr#endif
for 1.x compatibility. Further, the struct willnot be the actualdescriptor anymore, only it’s type number will be updated.After successful registration, you must thus fetch the actualdtype with:
inttype_num=PyArray_RegisterDataType(&my_descr_proto);if(type_num<0){/*error*/}PyArray_Descr*my_descr=PyArray_DescrFromType(type_num);
With these two changes, the code should compile and work on both 1.xand 2.x or later.
In the unlikely case that you are heap allocating the dtype struct youshould free it again on NumPy 2, since a copy is made.The struct is not a valid Python object, so do not use
Py_DECREF
on it.Register a data-type as a new user-defined data type forarrays. The type must have most of its entries filled in. This isnot always checked and errors can produce segfaults. Inparticular, the typeobj member of the
dtype
structure must befilled with a Python type that has a fixed-size element-size thatcorresponds to the elsize member ofdtype. Also thef
member must have the required functions: nonzero, copyswap,copyswapn, getitem, setitem, and cast (some of the cast functionsmay beNULL
if no support is desired). To avoid confusion, youshould choose a unique character typecode but this is not enforcedand not relied on internally.A user-defined type number is returned that uniquely identifiesthe type. A pointer to the new structure can then be obtained from
PyArray_DescrFromType
using the returned type number. A -1 isreturned if an error occurs. If thisdtype has already beenregistered (checked only by the address of the pointer), thenreturn the previously-assigned type-number.The number of user DTypes known to numpy is stored in
NPY_NUMUSERTYPES
, a static global variable that is public in theC API. Accessing this symbol is inherentlynot thread-safe. Iffor some reason you need to use this API in a multithreaded context,you will need to add your own locking, NumPy does not ensure newdata types can be added in a thread-safe manner.
- intPyArray_RegisterCastFunc(PyArray_Descr*descr,inttotype,PyArray_VectorUnaryFunc*castfunc)#
Register a low-level casting function,castfunc, to convertfrom the data-type,descr, to the given data-type number,totype. Any old casting function is over-written. A
0
isreturned on success or a-1
on failure.- typePyArray_VectorUnaryFunc#
The function pointer type for low-level casting functions.
- typePyArray_VectorUnaryFunc#
- intPyArray_RegisterCanCast(PyArray_Descr*descr,inttotype,NPY_SCALARKINDscalar)#
Register the data-type number,totype, as castable fromdata-type object,descr, of the givenscalar kind. Usescalar =
NPY_NOSCALAR
to register that an array of data-typedescr can be cast safely to a data-type whose type_number istotype. The return value is 0 on success or -1 on failure.
Special functions for NPY_OBJECT#
Warning
When working with arrays or buffers filled with objects NumPy tries toensure such buffers are filled withNone
before any data may be read.However, code paths may existed where an array is only initialized toNULL
.NumPy itself acceptsNULL
as an alias forNone
, but mayassert
non-NULL
when compiled in debug mode.
Because NumPy is not yet consistent about initialization with None,usersmust expect a value ofNULL
when working with buffers createdby NumPy. Usersshould also ensure to pass fully initialized buffersto NumPy, since NumPy may make this a strong requirement in the future.
There is currently an intention to ensure that NumPy always initializesobject arrays before they may be read. Any failure to do so will beregarded as a bug.In the future, users may be able to rely on non-NULL values when readingfrom any array, although exceptions for writing to freshly created arraysmay remain (e.g. for output arrays in ufunc code). As of NumPy 1.23known code paths exists where proper filling is not done.
- intPyArray_INCREF(PyArrayObject*op)#
Used for an array,op, that contains any Python objects. Itincrements the reference count of every object in the arrayaccording to the data-type ofop. A -1 is returned if an erroroccurs, otherwise 0 is returned.
- voidPyArray_Item_INCREF(char*ptr,PyArray_Descr*dtype)#
A function to INCREF all the objects at the locationptraccording to the data-typedtype. Ifptr is the start of astructured type with an object at any offset, then this will (recursively)increment the reference count of all object-like items in thestructured type.
- intPyArray_XDECREF(PyArrayObject*op)#
Used for an array,op, that contains any Python objects. Itdecrements the reference count of every object in the arrayaccording to the data-type ofop. Normal return value is 0. A-1 is returned if an error occurs.
- voidPyArray_Item_XDECREF(char*ptr,PyArray_Descr*dtype)#
A function to XDECREF all the object-like items at the locationptr as recorded in the data-type,dtype. This worksrecursively so that if
dtype
itself has fields with data-typesthat contain object-like items, all the object-like fields will beXDECREF'd
.
- intPyArray_SetWritebackIfCopyBase(PyArrayObject*arr,PyArrayObject*base)#
Precondition:
arr
is a copy ofbase
(though possibly with differentstrides, ordering, etc.) Sets theNPY_ARRAY_WRITEBACKIFCOPY
flagandarr->base
, and setbase
to READONLY. CallPyArray_ResolveWritebackIfCopy
before callingPy_DECREF
in order to copy any changes back tobase
andreset the READONLY flag.Returns 0 for success, -1 for failure.
Array flags#
Theflags
attribute of thePyArrayObject
structure containsimportant information about the memory used by the array (pointed toby the data member) This flag information must be kept accurate orstrange results and even segfaults may result.
There are 6 (binary) flags that describe the memory area used by thedata buffer. These constants are defined inarrayobject.h
anddetermine the bit-position of the flag. Python exposes a niceattribute- based interface as well as a dictionary-like interface forgetting (and, if appropriate, setting) these flags.
Memory areas of all kinds can be pointed to by an ndarray, necessitatingthese flags. If you get an arbitraryPyArrayObject
in C-code, youneed to be aware of the flags that are set. If you need to guaranteea certain kind of array (likeNPY_ARRAY_C_CONTIGUOUS
andNPY_ARRAY_BEHAVED
), then pass these requirements into thePyArray_FromAny function.
In versions 1.6 and earlier of NumPy, the following flagsdid not have the _ARRAY_ macro namespace in them. That formof the constant names is deprecated in 1.7.
Basic Array Flags#
An ndarray can have a data segment that is not a simple contiguouschunk of well-behaved memory you can manipulate. It may not be alignedwith word boundaries (very important on some platforms). It might haveits data in a different byte-order than the machine recognizes. Itmight not be writeable. It might be in Fortran-contiguous order. Thearray flags are used to indicate what can be said about dataassociated with an array.
- NPY_ARRAY_C_CONTIGUOUS#
The data area is in C-style contiguous order (last index varies thefastest).
- NPY_ARRAY_F_CONTIGUOUS#
The data area is in Fortran-style contiguous order (first index variesthe fastest).
Note
Arrays can be both C-style and Fortran-style contiguous simultaneously.This is clear for 1-dimensional arrays, but can also be true for higherdimensional arrays.
Even for contiguous arrays a stride for a given dimensionarr.strides[dim]
may bearbitrary ifarr.shape[dim]==1
or the array has no elements.It doesnot generally hold thatself.strides[-1]==self.itemsize
for C-style contiguous arrays orself.strides[0]==self.itemsize
forFortran-style contiguous arrays is true. The correct way to access theitemsize
of an array from the C API isPyArray_ITEMSIZE(arr)
.
- NPY_ARRAY_OWNDATA#
The data area is owned by this array. Should never be set manually, insteadcreate a
PyObject
wrapping the data and set the array’s base to thatobject. For an example, see the test intest_mem_policy
.
- NPY_ARRAY_ALIGNED#
The data area and all array elements are aligned appropriately.
- NPY_ARRAY_WRITEABLE#
The data area can be written to.
Notice that the above 3 flags are defined so that a new, well-behaved array has these flags defined as true.
- NPY_ARRAY_WRITEBACKIFCOPY#
The data area represents a (well-behaved) copy whose informationshould be transferred back to the original when
PyArray_ResolveWritebackIfCopy
is called.This is a special flag that is set if this array represents a copymade because a user required certain flags in
PyArray_FromAny
and a copy had to be made of some otherarray (and the user asked for this flag to be set in such asituation). The base attribute then points to the “misbehaved”array (which is set read_only).PyArray_ResolveWritebackIfCopy
will copy its contents back to the “misbehaved”array (casting if necessary) and will reset the “misbehaved” arraytoNPY_ARRAY_WRITEABLE
. If the “misbehaved” array was notNPY_ARRAY_WRITEABLE
to begin with thenPyArray_FromAny
would have returned an error becauseNPY_ARRAY_WRITEBACKIFCOPY
would not have been possible.
PyArray_UpdateFlags
(obj, flags) will update theobj->flags
forflags
which can be any ofNPY_ARRAY_C_CONTIGUOUS
,NPY_ARRAY_F_CONTIGUOUS
,NPY_ARRAY_ALIGNED
, orNPY_ARRAY_WRITEABLE
.
Combinations of array flags#
- NPY_ARRAY_BEHAVED#
- NPY_ARRAY_CARRAY#
- NPY_ARRAY_CARRAY_RO#
- NPY_ARRAY_FARRAY#
- NPY_ARRAY_FARRAY_RO#
- NPY_ARRAY_DEFAULT#
- NPY_ARRAY_IN_ARRAY#
- NPY_ARRAY_IN_FARRAY#
- NPY_ARRAY_OUT_ARRAY#
NPY_ARRAY_C_CONTIGUOUS
|NPY_ARRAY_WRITEABLE
|NPY_ARRAY_ALIGNED
- NPY_ARRAY_OUT_FARRAY#
NPY_ARRAY_F_CONTIGUOUS
|NPY_ARRAY_WRITEABLE
|NPY_ARRAY_ALIGNED
- NPY_ARRAY_INOUT_ARRAY#
NPY_ARRAY_C_CONTIGUOUS
|NPY_ARRAY_WRITEABLE
|NPY_ARRAY_ALIGNED
|NPY_ARRAY_WRITEBACKIFCOPY
- NPY_ARRAY_INOUT_FARRAY#
NPY_ARRAY_F_CONTIGUOUS
|NPY_ARRAY_WRITEABLE
|NPY_ARRAY_ALIGNED
|NPY_ARRAY_WRITEBACKIFCOPY
- NPY_ARRAY_UPDATE_ALL#
NPY_ARRAY_C_CONTIGUOUS
|NPY_ARRAY_F_CONTIGUOUS
|NPY_ARRAY_ALIGNED
Flag-like constants#
These constants are used inPyArray_FromAny
(and its macro forms) tospecify desired properties of the new array.
- NPY_ARRAY_FORCECAST#
Cast to the desired type, even if it can’t be done without losinginformation.
- NPY_ARRAY_ENSURECOPY#
Make sure the resulting array is a copy of the original.
- NPY_ARRAY_ENSUREARRAY#
Make sure the resulting object is an actual ndarray, and not a sub-class.
These constants are used inPyArray_CheckFromAny
(and its macro forms)to specify desired properties of the new array.
- NPY_ARRAY_NOTSWAPPED#
Make sure the returned array has a data-type descriptor that is inmachine byte-order, over-riding any specification in thedtypeargument. Normally, the byte-order requirement is determined bythedtype argument. If this flag is set and the dtype argumentdoes not indicate a machine byte-order descriptor (or is NULL andthe object is already an array with a data-type descriptor that isnot in machine byte- order), then a new data-type descriptor iscreated and used with its byte-order field set to native.
- NPY_ARRAY_BEHAVED_NS#
NPY_ARRAY_ALIGNED
|NPY_ARRAY_WRITEABLE
|NPY_ARRAY_NOTSWAPPED
- NPY_ARRAY_ELEMENTSTRIDES#
Make sure the returned array has strides that are multiples of theelement size.
Flag checking#
For all of these macrosarr must be an instance of a (subclass of)PyArray_Type
.
- intPyArray_CHKFLAGS(constPyArrayObject*arr,intflags)#
The first parameter, arr, must be an ndarray or subclass. Theparameter,flags, should be an integer consisting of bitwisecombinations of the possible flags an array can have:
NPY_ARRAY_C_CONTIGUOUS
,NPY_ARRAY_F_CONTIGUOUS
,NPY_ARRAY_OWNDATA
,NPY_ARRAY_ALIGNED
,NPY_ARRAY_WRITEABLE
,NPY_ARRAY_WRITEBACKIFCOPY
.
- intPyArray_IS_C_CONTIGUOUS(constPyArrayObject*arr)#
Evaluates true ifarr is C-style contiguous.
- intPyArray_IS_F_CONTIGUOUS(constPyArrayObject*arr)#
Evaluates true ifarr is Fortran-style contiguous.
- intPyArray_ISFORTRAN(constPyArrayObject*arr)#
Evaluates true ifarr is Fortran-style contiguous andnotC-style contiguous.
PyArray_IS_F_CONTIGUOUS
is the correct way to test for Fortran-style contiguity.
- intPyArray_ISWRITEABLE(constPyArrayObject*arr)#
Evaluates true if the data area ofarr can be written to
- intPyArray_ISALIGNED(constPyArrayObject*arr)#
Evaluates true if the data area ofarr is properly aligned onthe machine.
- intPyArray_ISBEHAVED(constPyArrayObject*arr)#
Evaluates true if the data area ofarr is aligned and writeableand in machine byte-order according to its descriptor.
- intPyArray_ISBEHAVED_RO(constPyArrayObject*arr)#
Evaluates true if the data area ofarr is aligned and in machinebyte-order.
- intPyArray_ISCARRAY(constPyArrayObject*arr)#
Evaluates true if the data area ofarr is C-style contiguous,and
PyArray_ISBEHAVED
(arr) is true.
- intPyArray_ISFARRAY(constPyArrayObject*arr)#
Evaluates true if the data area ofarr is Fortran-stylecontiguous and
PyArray_ISBEHAVED
(arr) is true.
- intPyArray_ISCARRAY_RO(constPyArrayObject*arr)#
Evaluates true if the data area ofarr is C-style contiguous,aligned, and in machine byte-order.
- intPyArray_ISFARRAY_RO(constPyArrayObject*arr)#
Evaluates true if the data area ofarr is Fortran-stylecontiguous, aligned, and in machine byte-order.
- intPyArray_ISONESEGMENT(constPyArrayObject*arr)#
Evaluates true if the data area ofarr consists of a single(C-style or Fortran-style) contiguous segment.
- voidPyArray_UpdateFlags(PyArrayObject*arr,intflagmask)#
The
NPY_ARRAY_C_CONTIGUOUS
,NPY_ARRAY_ALIGNED
, andNPY_ARRAY_F_CONTIGUOUS
array flags can be “calculated” from thearray object itself. This routine updates one or more of theseflags ofarr as specified inflagmask by performing therequired calculation.
Warning
It is important to keep the flags updated (usingPyArray_UpdateFlags
can help) whenever a manipulation with anarray is performed that might cause them to change. Latercalculations in NumPy that rely on the state of these flags do notrepeat the calculation to update them.
- intPyArray_FailUnlessWriteable(PyArrayObject*obj,constchar*name)#
This function does nothing and returns 0 ifobj is writeable.It raises an exception and returns -1 ifobj is not writeable.It may also do other house-keeping, such as issuing warnings onarrays which are transitioning to become views. Always call thisfunction at some point before writing to an array.
name is a name for the array, used to give better error messages.It can be something like “assignment destination”, “output array”,or even just “array”.
ArrayMethod API#
ArrayMethod loops are intended as a generic mechanism for writing loopsover arrays, including ufunc loops and casts. The public API is defined in thenumpy/dtype_api.h
header. SeePyArrayMethod_Context and PyArrayMethod_Spec fordocumentation on the C structs exposed in the ArrayMethod API.
Slots and Typedefs#
These are used to identify which kind of function an ArrayMethod slotimplements. SeeSlots and Typedefs below for documentation onthe functions that must be implemented for each slot.
- NPY_METH_resolve_descriptors#
- typedefNPY_CASTING(PyArrayMethod_ResolveDescriptors)(structPyArrayMethodObject_tag*method,PyArray_DTypeMeta*const*dtypes,PyArray_Descr*const*given_descrs,PyArray_Descr**loop_descrs,npy_intp*view_offset)#
The function used to set the descriptors for an operation based onthe descriptors of the operands. For example, a ufunc operation withtwo input operands and one output operand that is called without
out
being set in the python API,resolve_descriptors
will bepassed the descriptors for the two operands and determine the correctdescriptor to use for the output based on the output DType set forthe ArrayMethod. Ifout
is set, then the output descriptor wouldbe passed in as well and should not be overridden.Themethod is a pointer to the underlying cast or ufunc loop. Inthe future we may expose this struct publicly but for now this is anopaque pointer and the method cannot be inspected. Thedtypes is an
nargs
length array ofPyArray_DTypeMeta
pointers,given_descrs is annargs
length array of input descriptorinstances (output descriptors may be NULL if no output was providedby the user), andloop_descrs is annargs
length array ofdescriptors that must be filled in by the resolve descriptorsimplementation.view_offset is currently only interesting forcasts and can normally be ignored. When a cast does not require anyoperation, this can be signalled by settingview_offset
to 0. Onerror, you must return(NPY_CASTING)-1
with an error set.
- NPY_METH_strided_loop#
- NPY_METH_contiguous_loop#
- NPY_METH_unaligned_strided_loop#
- NPY_METH_unaligned_contiguous_loop#
One dimensional strided loops implementing the behavior (either aufunc or cast). In most cases,
NPY_METH_strided_loop
is thegeneric and only version that needs to be implemented.NPY_METH_contiguous_loop
can be implemented additionally as amore light-weight/faster version and it is used when all inputs andoutputs are contiguous.To deal with possibly unaligned data, NumPy needs to be able to copyunaligned to aligned data. When implementing a new DType, the “cast”or copy for it needs to implement
NPY_METH_unaligned_strided_loop
. Unlike the normal versions,this loop must not assume that the data can be accessed in an alignedfashion. These loops must copy each value before accessing orstoring:type_inin_value;type_outout_valuememcpy(&value,in_data,sizeof(type_in));out_value=in_value;memcpy(out_data,&out_value,sizeof(type_out)
while a normal loop can just use:
*(type_out*)out_data=*(type_in)in_data;
The unaligned loops are currently only used in casts and will neverbe picked in ufuncs (ufuncs create a temporary copy to ensure alignedinputs). These slot IDs are ignored when
NPY_METH_get_loop
isdefined, where instead whichever loop returned by theget_loop
function is used.
- NPY_METH_contiguous_indexed_loop#
A specialized inner-loop option to speed up common
ufunc.at
computations.
- typedefint(PyArrayMethod_StridedLoop)(PyArrayMethod_Context*context,char*const*data,constnpy_intp*dimensions,constnpy_intp*strides,NpyAuxData*auxdata)#
An implementation of an ArrayMethod loop. All of the loop slot IDslisted above must provide a
PyArrayMethod_StridedLoop
implementation. Thecontext is a struct containing context for theloop operation - in particular the input descriptors. Thedata arean array of pointers to the beginning of the input and output arraybuffers. Thedimensions are the loop dimensions for theoperation. Thestrides are annargs
length array of strides foreach input. Theauxdata is an optional set of auxiliary data thatcan be passed in to the loop - helpful to turn on and off optionalbehavior or reduce boilerplate by allowing similar ufuncs to shareloop implementations or to allocate space that is persistent overmultiple strided loop calls.
- NPY_METH_get_loop#
Allows more fine-grained control over loop selection. Accepts animplementation of PyArrayMethod_GetLoop, which in turn returns astrided loop implementation. If
NPY_METH_get_loop
is defined,the other loop slot IDs are ignored, if specified.
- typedefint(PyArrayMethod_GetLoop)(PyArrayMethod_Context*context,intaligned,intmove_references,constnpy_intp*strides,PyArrayMethod_StridedLoop**out_loop,NpyAuxData**out_transferdata,NPY_ARRAYMETHOD_FLAGS*flags);#
Sets the loop to use for an operation at runtime. Thecontext is theruntime context for the operation.aligned indicates whether the dataaccess for the loop is aligned (1) or unaligned (0).move_referencesindicates whether embedded references in the data should be copied.stridesare the strides for the input array,out_loop is a pointer that must befilled in with a pointer to the loop implementation.out_transferdata canbe optionally filled in to allow passing in extra user-defined context to anoperation.flags must be filled in with ArrayMethod flags relevant for theoperation. This is for example necessary to indicate if the inner looprequires the Python GIL to be held.
- NPY_METH_get_reduction_initial#
- typedefint(PyArrayMethod_GetReductionInitial)(PyArrayMethod_Context*context,npy_boolreduction_is_empty,char*initial)#
Query an ArrayMethod for the initial value for use in reduction. Thecontext is the ArrayMethod context, mainly to access the inputdescriptors.reduction_is_empty indicates whether the reduction isempty. When it is, the value returned may differ. In this case it is a“default” value that may differ from the “identity” value normally used.For example:
0.0
is the default forsum([])
. But-0.0
is the correctidentity otherwise as it preserves the sign forsum([-0.0])
.We use no identity for object, but return the default of
0
and1
for the emptysum([],dtype=object)
andprod([],dtype=object)
.This allowsnp.sum(np.array(["a","b"],dtype=object))
to work.-inf
orINT_MIN
formax
is an identity, but at leastINT_MIN
not a gooddefault when there are no items.
initial is a pointer to the data for the initial value, which should befilled in. Returns -1, 0, or 1 indicating error, no initial value, and theinitial value being successfully filled. Errors must not be given when noinitial value is correct, since NumPy may call this even when it is notstrictly necessary to do so.
Flags#
- enumNPY_ARRAYMETHOD_FLAGS#
These flags allow switching on and off custom runtime behavior forArrayMethod loops. For example, if a ufunc cannot possibly trigger floatingpoint errors, then the
NPY_METH_NO_FLOATINGPOINT_ERRORS
flag should beset on the ufunc when it is registered.- enumeratorNPY_METH_REQUIRES_PYAPI#
Indicates the method must hold the GIL. If this flag is not set, the GILis released before the loop is called.
- enumeratorNPY_METH_NO_FLOATINGPOINT_ERRORS#
Indicates the method cannot generate floating errors, so checking forfloating errors after the loop completes can be skipped.
- enumeratorNPY_METH_SUPPORTS_UNALIGNED#
Indicates the method supports unaligned access.
- enumeratorNPY_METH_IS_REORDERABLE#
Indicates that the result of applying the loop repeatedly (for example, ina reduction operation) does not depend on the order of application.
- enumeratorNPY_METH_RUNTIME_FLAGS#
The flags that can be changed at runtime.
- enumeratorNPY_METH_REQUIRES_PYAPI#
Typedefs#
Typedefs for functions that users of the ArrayMethod API can implement aredescribed below.
- typedefint(PyArrayMethod_TraverseLoop)(void*traverse_context,constPyArray_Descr*descr,char*data,npy_intpsize,npy_intpstride,NpyAuxData*auxdata)#
A traverse loop working on a single array. This is similar to the generalstrided-loop function. This is designed for loops that need to visit everyelement of a single array.
Currently this is used for array clearing, via the
NPY_DT_get_clear_loop
DType API hook, and zero-filling, via theNPY_DT_get_fill_zero_loop
DType API hook. These are most useful for handling arrays storing embeddedreferences to python objects or heap-allocated data.Thedescr is the descriptor for the array,data is a pointer to the arraybuffer,size is the 1D size of the array buffer,stride is the stride,andauxdata is optional extra data for the loop.
Thetraverse_context is passed in because we may need to pass inInterpreter state or similar in the future, but we don’t want to pass in afull context (with pointers to dtypes, method, caller which all make no sensefor a traverse function). We assume for now that this context can be justpassed through in the future (for structured dtypes).
- typedefint(PyArrayMethod_GetTraverseLoop)(void*traverse_context,constPyArray_Descr*descr,intaligned,npy_intpfixed_stride,PyArrayMethod_TraverseLoop**out_loop,NpyAuxData**out_auxdata,NPY_ARRAYMETHOD_FLAGS*flags)#
Simplified get_loop function specific to dtype traversal
It should set the flags needed for the traversal loop and setout_loop to theloop function, which must be a valid
PyArrayMethod_TraverseLoop
pointer. Currently this is used for zero-filling and clearing arrays storingembedded references.
API Functions and Typedefs#
These functions are part of the main numpy array API and were added alongwith the rest of the ArrayMethod API.
- intPyUFunc_AddLoopFromSpec(PyObject*ufunc,PyArrayMethod_Spec*spec)#
Add loop directly to a ufunc from a given ArrayMethod spec.the main ufunc registration function. This adds a new implementation/loopto a ufunc. It replacesPyUFunc_RegisterLoopForType.
- intPyUFunc_AddPromoter(PyObject*ufunc,PyObject*DType_tuple,PyObject*promoter)#
Note that currently the output dtypes are always
NULL
unless they arealso part of the signature. This is an implementation detail and couldchange in the future. However, in general promoters should not have aneed for output dtypes.Register a new promoter for a ufunc. The first argument is the ufunc toregister the promoter with. The second argument is a Python tuple containingDTypes or None matching the number of inputs and outputs for the ufuncs. Thelast argument is a promoter is a function stored in a PyCapsule. It ispassed the operation and requested DType signatures and can mutate it toattempt a new search for a matching loop/promoter.
- typedefint(PyArrayMethod_PromoterFunction)(PyObject*ufunc,PyArray_DTypeMeta*constop_dtypes[],PyArray_DTypeMeta*constsignature[],PyArray_DTypeMeta*new_op_dtypes[])#
Type of the promoter function, which must be wrapped into a
PyCapsule
with name"numpy._ufunc_promoter"
. It is passed theoperation and requested DType signatures and can mutate the signatures toattempt a search for a new loop or promoter that can accomplish the operationby casting the inputs to the “promoted” DTypes.
- intPyUFunc_GiveFloatingpointErrors(constchar*name,intfpe_errors)#
Checks for a floating point error after performing a floating pointoperation in a manner that takes into account the error signaling configuredvia
numpy.errstate
. Takes the name of the operation to use in the errormessage and an integer flag that is one ofNPY_FPE_DIVIDEBYZERO
,NPY_FPE_OVERFLOW
,NPY_FPE_UNDERFLOW
,NPY_FPE_INVALID
to indicatewhich error to check for.Returns -1 on failure (an error was raised) and 0 on success.
- intPyUFunc_AddWrappingLoop(PyObject*ufunc_obj,PyArray_DTypeMeta*new_dtypes[],PyArray_DTypeMeta*wrapped_dtypes[],PyArrayMethod_TranslateGivenDescriptors*translate_given_descrs,PyArrayMethod_TranslateLoopDescriptors*translate_loop_descrs)#
Allows creating of a fairly lightweight wrapper around an existingufunc loop. The idea is mainly for units, as this is currentlyslightly limited in that it enforces that you cannot use a loop fromanother ufunc.
- typedefint(PyArrayMethod_TranslateGivenDescriptors)(intnin,intnout,PyArray_DTypeMeta*wrapped_dtypes[],PyArray_Descr*given_descrs[],PyArray_Descr*new_descrs[]);#
The function to convert the given descriptors (passed in to
resolve_descriptors
) and translates them for the wrapped loop.The new descriptors MUST be viewable with the old ones,NULL must besupported (for output arguments) and should normally be forwarded.The output of of this function will be used to constructviews of the arguments as if they were the translated dtypes anddoes not use a cast. This means this mechanism is mostly useful forDTypes that “wrap” another DType implementation. For example, a unitDType could use this to wrap an existing floating point DTypewithout needing to re-implement low-level ufunc logic. In the unitexample,
resolve_descriptors
would handle computing the outputunit from the input unit.
- typedefint(PyArrayMethod_TranslateLoopDescriptors)(intnin,intnout,PyArray_DTypeMeta*new_dtypes[],PyArray_Descr*given_descrs[],PyArray_Descr*original_descrs[],PyArray_Descr*loop_descrs[]);#
The function to convert the actual loop descriptors (as returned bythe originalresolve_descriptors function) to the ones the outputarray should use. This function must return “viewable” types, it mustnot mutate them in any form that would break the inner-loop logic.Does not need to support NULL.
Wrapping Loop Example#
Suppose you want to wrap thefloat64
multiply implementation for aWrappedDoubleDType
. You would add a wrapping loop like so:
PyArray_DTypeMeta*orig_dtypes[3]={&WrappedDoubleDType,&WrappedDoubleDType,&WrappedDoubleDType};PyArray_DTypeMeta*wrapped_dtypes[3]={&PyArray_Float64DType,&PyArray_Float64DType,&PyArray_Float64DType}PyObject*mod=PyImport_ImportModule("numpy");if(mod==NULL){return-1;}PyObject*multiply=PyObject_GetAttrString(mod,"multiply");Py_DECREF(mod);if(multiply==NULL){return-1;}intres=PyUFunc_AddWrappingLoop(multiply,orig_dtypes,wrapped_dtypes,&translate_given_descrs&translate_loop_descrs);Py_DECREF(multiply);
Note that this also requires two functions to be defined above thiscode:
staticinttranslate_given_descrs(intnin,intnout,PyArray_DTypeMeta*NPY_UNUSED(wrapped_dtypes[]),PyArray_Descr*given_descrs[],PyArray_Descr*new_descrs[]){for(inti=0;i<nin+nout;i++){if(given_descrs[i]==NULL){new_descrs[i]=NULL;}else{new_descrs[i]=PyArray_DescrFromType(NPY_DOUBLE);}}return0;}staticinttranslate_loop_descrs(intnin,intNPY_UNUSED(nout),PyArray_DTypeMeta*NPY_UNUSED(new_dtypes[]),PyArray_Descr*given_descrs[],PyArray_Descr*original_descrs[],PyArray_Descr*loop_descrs[]){// more complicated parametric DTypes may need to// to do additional checking, but we know the wrapped// DTypes *have* to be float64 for this example.loop_descrs[0]=PyArray_DescrFromType(NPY_FLOAT64);Py_INCREF(loop_descrs[0]);loop_descrs[1]=PyArray_DescrFromType(NPY_FLOAT64);Py_INCREF(loop_descrs[1]);loop_descrs[2]=PyArray_DescrFromType(NPY_FLOAT64);Py_INCREF(loop_descrs[2]);}
API for calling array methods#
Conversion#
- PyObject*PyArray_GetField(PyArrayObject*self,PyArray_Descr*dtype,intoffset)#
Equivalent to
ndarray.getfield
(self,dtype,offset). This functionsteals a referencetoPyArray_Descr
and returns a new array of the givendtype usingthe data in the current array at a specifiedoffset in bytes. Theoffset plus the itemsize of the new array type must be less thanself->descr->elsize
or an error is raised. The same shape and stridesas the original array are used. Therefore, this function has theeffect of returning a field from a structured array. But, it can alsobe used to select specific bytes or groups of bytes from any arraytype.
- intPyArray_SetField(PyArrayObject*self,PyArray_Descr*dtype,intoffset,PyObject*val)#
Equivalent to
ndarray.setfield
(self,val,dtype,offset). Set the field starting atoffset in bytes and of the givendtype toval. Theoffset plusdtype ->elsize must be lessthanself ->descr->elsize or an error is raised. Otherwise, theval argument is converted to an array and copied into the fieldpointed to. If necessary, the elements ofval are repeated tofill the destination array, But, the number of elements in thedestination must be an integer multiple of the number of elementsinval.
- PyObject*PyArray_Byteswap(PyArrayObject*self,npy_boolinplace)#
Equivalent to
ndarray.byteswap
(self,inplace). Return an arraywhose data area is byteswapped. Ifinplace is non-zero, then dothe byteswap inplace and return a reference to self. Otherwise,create a byteswapped copy and leave self unchanged.
- PyObject*PyArray_NewCopy(PyArrayObject*old,NPY_ORDERorder)#
Equivalent to
ndarray.copy
(self,fortran). Make a copy of theold array. The returned array is always aligned and writeablewith data interpreted the same as the old array. Iforder isNPY_CORDER
, then a C-style contiguous array is returned. Iforder isNPY_FORTRANORDER
, then a Fortran-style contiguousarray is returned. Iforder isNPY_ANYORDER
, then the arrayreturned is Fortran-style contiguous only if the old one is;otherwise, it is C-style contiguous.
- PyObject*PyArray_ToList(PyArrayObject*self)#
Equivalent to
ndarray.tolist
(self). Return a nested Python listfromself.
- PyObject*PyArray_ToString(PyArrayObject*self,NPY_ORDERorder)#
Equivalent to
ndarray.tobytes
(self,order). Return the bytesof this array in a Python string.
- PyObject*PyArray_ToFile(PyArrayObject*self,FILE*fp,char*sep,char*format)#
Write the contents ofself to the file pointerfp in C-stylecontiguous fashion. Write the data as binary bytes ifsep is thestring “”or
NULL
. Otherwise, write the contents ofself astext using thesep string as the item separator. Each item willbe printed to the file. If theformat string is notNULL
or“”, then it is a Python print statement format string showing howthe items are to be written.
- intPyArray_Dump(PyObject*self,PyObject*file,intprotocol)#
Pickle the object inself to the givenfile (either a stringor a Python file object). Iffile is a Python string it isconsidered to be the name of a file which is then opened in binarymode. The givenprotocol is used (ifprotocol is negative, orthe highest available is used). This is a simple wrapper aroundcPickle.dump(self,file,protocol).
- PyObject*PyArray_Dumps(PyObject*self,intprotocol)#
Pickle the object inself to a Python string and return it. Usethe Pickleprotocol provided (or the highest available ifprotocol is negative).
- intPyArray_FillWithScalar(PyArrayObject*arr,PyObject*obj)#
Fill the array,arr, with the given scalar object,obj. Theobject is first converted to the data type ofarr, and thencopied into every location. A -1 is returned if an error occurs,otherwise 0 is returned.
- PyObject*PyArray_View(PyArrayObject*self,PyArray_Descr*dtype,PyTypeObject*ptype)#
Equivalent to
ndarray.view
(self,dtype). Return a newview of the arrayself as possibly a different data-type,dtype,and different array subclassptype.Ifdtype is
NULL
, then the returned array will have the samedata type asself. The new data-type must be consistent with thesize ofself. Either the itemsizes must be identical, orself mustbe single-segment and the total number of bytes must be the same.In the latter case the dimensions of the returned array will bealtered in the last (or first for Fortran-style contiguous arrays)dimension. The data area of the returned array and self is exactlythe same.
Shape Manipulation#
- PyObject*PyArray_Newshape(PyArrayObject*self,PyArray_Dims*newshape,NPY_ORDERorder)#
Result will be a new array (pointing to the same memory locationasself if possible), but having a shape given bynewshape.If the new shape is not compatible with the strides ofself,then a copy of the array with the new specified shape will bereturned.
- PyObject*PyArray_Reshape(PyArrayObject*self,PyObject*shape)#
Equivalent to
ndarray.reshape
(self,shape) whereshape is asequence. Convertsshape to aPyArray_Dims
structure andcallsPyArray_Newshape
internally.For back-ward compatibility – Not recommended
- PyObject*PyArray_Squeeze(PyArrayObject*self)#
Equivalent to
ndarray.squeeze
(self). Return a new view ofselfwith all of the dimensions of length 1 removed from the shape.
Warning
matrix objects are always 2-dimensional. Therefore,PyArray_Squeeze
has no effect on arrays of matrix sub-class.
- PyObject*PyArray_SwapAxes(PyArrayObject*self,inta1,inta2)#
Equivalent to
ndarray.swapaxes
(self,a1,a2). The returnedarray is a new view of the data inself with the given axes,a1 anda2, swapped.
- PyObject*PyArray_Resize(PyArrayObject*self,PyArray_Dims*newshape,intrefcheck,NPY_ORDERfortran)#
Equivalent to
ndarray.resize
(self,newshape, refcheck=
refcheck, order= fortran ). This function only works onsingle-segment arrays. It changes the shape ofself inplace andwill reallocate the memory forself ifnewshape has adifferent total number of elements then the old shape. Ifreallocation is necessary, thenself must own its data, haveself ->base==NULL
, haveself ->weakrefs==NULL
, and(unless refcheck is 0) not be referenced by any other array.The fortran argument can beNPY_ANYORDER
,NPY_CORDER
,orNPY_FORTRANORDER
. It currently has no effect. Eventuallyit could be used to determine how the resize operation should viewthe data when constructing a differently-dimensioned array.Returns None on success and NULL on error.
- PyObject*PyArray_Transpose(PyArrayObject*self,PyArray_Dims*permute)#
Equivalent to
ndarray.transpose
(self,permute). Permute theaxes of the ndarray objectself according to the data structurepermute and return the result. Ifpermute isNULL
, thenthe resulting array has its axes reversed. For example ifselfhas shape\(10\times20\times30\), andpermute.ptr
is(0,2,1) the shape of the result is\(10\times30\times20.\) Ifpermute isNULL
, the shape of the result is\(30\times20\times10.\)
- PyObject*PyArray_Flatten(PyArrayObject*self,NPY_ORDERorder)#
Equivalent to
ndarray.flatten
(self,order). Return a 1-d copyof the array. Iforder isNPY_FORTRANORDER
the elements arescanned out in Fortran order (first-dimension varies thefastest). Iforder isNPY_CORDER
, the elements ofself
are scanned in C-order (last dimension varies the fastest). IforderNPY_ANYORDER
, then the result ofPyArray_ISFORTRAN
(self) is used to determine which orderto flatten.
- PyObject*PyArray_Ravel(PyArrayObject*self,NPY_ORDERorder)#
Equivalent toself.ravel(order). Same basic functionalityas
PyArray_Flatten
(self,order) except iforder is 0andself is C-style contiguous, the shape is altered but no copyis performed.
Item selection and manipulation#
- PyObject*PyArray_TakeFrom(PyArrayObject*self,PyObject*indices,intaxis,PyArrayObject*ret,NPY_CLIPMODEclipmode)#
Equivalent to
ndarray.take
(self,indices,axis,ret,clipmode) exceptaxis =None in Python is obtained by settingaxis =NPY_MAXDIMS
in C. Extract the items from selfindicated by the integer-valuedindices along the givenaxis.The clipmode argument can beNPY_RAISE
,NPY_WRAP
, orNPY_CLIP
to indicate what to do with out-of-bound indices. Theret argument can specify an output array rather than having onecreated internally.
- PyObject*PyArray_PutTo(PyArrayObject*self,PyObject*values,PyObject*indices,NPY_CLIPMODEclipmode)#
Equivalent toself.put(values,indices,clipmode). Putvalues intoself at the corresponding (flattened)indices. Ifvalues is too small it will be repeated asnecessary.
- PyObject*PyArray_PutMask(PyArrayObject*self,PyObject*values,PyObject*mask)#
Place thevalues inself wherever corresponding positions(using a flattened context) inmask are true. Themask andself arrays must have the same total number of elements. Ifvalues is too small, it will be repeated as necessary.
- PyObject*PyArray_Repeat(PyArrayObject*self,PyObject*op,intaxis)#
Equivalent to
ndarray.repeat
(self,op,axis). Copy theelements ofself,op times along the givenaxis. Eitherop is a scalar integer or a sequence of lengthself->dimensions[axis ] indicating how many times to repeat eachitem along the axis.
- PyObject*PyArray_Choose(PyArrayObject*self,PyObject*op,PyArrayObject*ret,NPY_CLIPMODEclipmode)#
Equivalent to
ndarray.choose
(self,op,ret,clipmode).Create a new array by selecting elements from the sequence ofarrays inop based on the integer values inself. The arraysmust all be broadcastable to the same shape and the entries inself should be between 0 and len(op). The output is placedinret unless it isNULL
in which case a new output iscreated. Theclipmode argument determines behavior for whenentries inself are not between 0 and len(op).- NPY_RAISE#
raise a ValueError;
- NPY_WRAP#
wrap values < 0 by adding len(op) and values >=len(op)by subtracting len(op) until they are in range;
- NPY_CLIP#
all values are clipped to the region [0, len(op) ).
- NPY_RAISE#
- PyObject*PyArray_Sort(PyArrayObject*self,intaxis,NPY_SORTKINDkind)#
Equivalent to
ndarray.sort
(self,axis,kind).Return an array with the items ofself sorted alongaxis. The arrayis sorted using the algorithm denoted bykind, which is an integer/enum pointingto the type of sorting algorithms used.
- PyObject*PyArray_ArgSort(PyArrayObject*self,intaxis)#
Equivalent to
ndarray.argsort
(self,axis).Return an array of indices such that selection of these indicesalong the givenaxis
would return a sorted version ofself. Ifself ->descris a data-type with fields defined, then self->descr->names is usedto determine the sort order. A comparison where the first field is equalwill use the second field and so on. To alter the sort order of astructured array, create a new data-type with a different order of namesand construct a view of the array with that new data-type.
- PyObject*PyArray_LexSort(PyObject*sort_keys,intaxis)#
Given a sequence of arrays (sort_keys) of the same shape,return an array of indices (similar to
PyArray_ArgSort
(…))that would sort the arrays lexicographically. A lexicographic sortspecifies that when two keys are found to be equal, the order isbased on comparison of subsequent keys. A merge sort (which leavesequal entries unmoved) is required to be defined for thetypes. The sort is accomplished by sorting the indices first usingthe firstsort_key and then using the secondsort_key and soforth. This is equivalent to the lexsort(sort_keys,axis)Python command. Because of the way the merge-sort works, be sureto understand the order thesort_keys must be in (reversed fromthe order you would use when comparing two elements).If these arrays are all collected in a structured array, then
PyArray_Sort
(…) can also be used to sort the arraydirectly.
- PyObject*PyArray_SearchSorted(PyArrayObject*self,PyObject*values,NPY_SEARCHSIDEside,PyObject*perm)#
Equivalent to
ndarray.searchsorted
(self,values,side,perm). Assumingself is a 1-d array in ascending order, then theoutput is an array of indices the same shape asvalues such that, ifthe elements invalues were inserted before the indices, the order ofself would be preserved. No checking is done on whether or not self isin ascending order.Theside argument indicates whether the index returned should be that ofthe first suitable location (if
NPY_SEARCHLEFT
) or of the last(ifNPY_SEARCHRIGHT
).Thesorter argument, if not
NULL
, must be a 1D array of integerindices the same length asself, that sorts it into ascending order.This is typically the result of a call toPyArray_ArgSort
(…)Binary search is used to find the required insertion points.
- intPyArray_Partition(PyArrayObject*self,PyArrayObject*ktharray,intaxis,NPY_SELECTKINDwhich)#
Equivalent to
ndarray.partition
(self,ktharray,axis,kind). Partitions the array so that the values of the element indexed byktharray are in the positions they would be if the array is fully sortedand places all elements smaller than the kth before and all elements equalor greater after the kth element. The ordering of all elements within thepartitions is undefined.Ifself->descr is a data-type with fields defined, thenself->descr->names is used to determine the sort order. A comparison wherethe first field is equal will use the second field and so on. To alter thesort order of a structured array, create a new data-type with a differentorder of names and construct a view of the array with that new data-type.Returns zero on success and -1 on failure.
- PyObject*PyArray_ArgPartition(PyArrayObject*op,PyArrayObject*ktharray,intaxis,NPY_SELECTKINDwhich)#
Equivalent to
ndarray.argpartition
(self,ktharray,axis,kind). Return an array of indices such that selection of these indicesalong the givenaxis
would return a partitioned version ofself.
- PyObject*PyArray_Diagonal(PyArrayObject*self,intoffset,intaxis1,intaxis2)#
Equivalent to
ndarray.diagonal
(self,offset,axis1,axis2). Return theoffset diagonals of the 2-d arrays defined byaxis1 andaxis2.
- npy_intpPyArray_CountNonzero(PyArrayObject*self)#
Counts the number of non-zero elements in the array objectself.
- PyObject*PyArray_Nonzero(PyArrayObject*self)#
Equivalent to
ndarray.nonzero
(self). Returns a tuple of indexarrays that select elements ofself that are nonzero. If (nd=PyArray_NDIM
(self
))==1, then a single index array isreturned. The index arrays have data typeNPY_INTP
. If atuple is returned (nd\(\neq\) 1), then its length is nd.
- PyObject*PyArray_Compress(PyArrayObject*self,PyObject*condition,intaxis,PyArrayObject*out)#
Equivalent to
ndarray.compress
(self,condition,axis). Return the elements alongaxis corresponding to elements ofcondition that are true.
Calculation#
Tip
Pass inNPY_RAVEL_AXIS
for axis in order to achieve the sameeffect that is obtained by passing inaxis=None
in Python(treating the array as a 1-d array).
Note
The out argument specifies where to place the result. If out isNULL, then the output array is created, otherwise the output isplaced in out which must be the correct size and type. A newreference to the output array is always returned even when outis not NULL. The caller of the routine has the responsibilitytoPy_DECREF
out if not NULL or a memory-leak will occur.
- PyObject*PyArray_ArgMax(PyArrayObject*self,intaxis,PyArrayObject*out)#
Equivalent to
ndarray.argmax
(self,axis). Return the index ofthe largest element ofself alongaxis.
- PyObject*PyArray_ArgMin(PyArrayObject*self,intaxis,PyArrayObject*out)#
Equivalent to
ndarray.argmin
(self,axis). Return the index ofthe smallest element ofself alongaxis.
- PyObject*PyArray_Max(PyArrayObject*self,intaxis,PyArrayObject*out)#
Equivalent to
ndarray.max
(self,axis). Returns the largestelement ofself along the givenaxis. When the result is a singleelement, returns a numpy scalar instead of an ndarray.
- PyObject*PyArray_Min(PyArrayObject*self,intaxis,PyArrayObject*out)#
Equivalent to
ndarray.min
(self,axis). Return the smallestelement ofself along the givenaxis. When the result is a singleelement, returns a numpy scalar instead of an ndarray.
- PyObject*PyArray_Ptp(PyArrayObject*self,intaxis,PyArrayObject*out)#
Return the difference between the largest element ofself alongaxis and thesmallest element ofself alongaxis. When the result is a singleelement, returns a numpy scalar instead of an ndarray.
Note
The rtype argument specifies the data-type the reduction shouldtake place over. This is important if the data-type of the arrayis not “large” enough to handle the output. By default, allinteger data-types are made at least as large asNPY_LONG
for the “add” and “multiply” ufuncs (which form the basis formean, sum, cumsum, prod, and cumprod functions).
- PyObject*PyArray_Mean(PyArrayObject*self,intaxis,intrtype,PyArrayObject*out)#
Equivalent to
ndarray.mean
(self,axis,rtype). Returns themean of the elements along the givenaxis, using the enumeratedtypertype as the data type to sum in. Default sum behavior isobtained usingNPY_NOTYPE
forrtype.
- PyObject*PyArray_Trace(PyArrayObject*self,intoffset,intaxis1,intaxis2,intrtype,PyArrayObject*out)#
Equivalent to
ndarray.trace
(self,offset,axis1,axis2,rtype). Return the sum (usingrtype as the data type ofsummation) over theoffset diagonal elements of the 2-d arraysdefined byaxis1 andaxis2 variables. A positive offsetchooses diagonals above the main diagonal. A negative offsetselects diagonals below the main diagonal.
- PyObject*PyArray_Clip(PyArrayObject*self,PyObject*min,PyObject*max)#
Equivalent to
ndarray.clip
(self,min,max). Clip an array,self, so that values larger thanmax are fixed tomax andvalues less thanmin are fixed tomin.
- PyObject*PyArray_Conjugate(PyArrayObject*self,PyArrayObject*out)#
Equivalent to
ndarray.conjugate
(self).Return the complex conjugate ofself. Ifself is not ofcomplex data type, then returnself with a reference.- Parameters:
self – Input array.
out – Output array. If provided, the result is placed into this array.
- Returns:
The complex conjugate ofself.
- PyObject*PyArray_Round(PyArrayObject*self,intdecimals,PyArrayObject*out)#
Equivalent to
ndarray.round
(self,decimals,out). Returnsthe array with elements rounded to the nearest decimal place. Thedecimal place is defined as the\(10^{-\textrm{decimals}}\)digit so that negativedecimals cause rounding to the nearest 10’s, 100’s, etc. If out isNULL
, then the output array is created, otherwise the output is placed inout which must be the correct size and type.
- PyObject*PyArray_Std(PyArrayObject*self,intaxis,intrtype,PyArrayObject*out)#
Equivalent to
ndarray.std
(self,axis,rtype). Return thestandard deviation using data alongaxis converted to data typertype.
- PyObject*PyArray_Sum(PyArrayObject*self,intaxis,intrtype,PyArrayObject*out)#
Equivalent to
ndarray.sum
(self,axis,rtype). Return 1-dvector sums of elements inself alongaxis. Perform the sumafter converting data to data typertype.
- PyObject*PyArray_CumSum(PyArrayObject*self,intaxis,intrtype,PyArrayObject*out)#
Equivalent to
ndarray.cumsum
(self,axis,rtype). Returncumulative 1-d sums of elements inself alongaxis. Performthe sum after converting data to data typertype.
- PyObject*PyArray_Prod(PyArrayObject*self,intaxis,intrtype,PyArrayObject*out)#
Equivalent to
ndarray.prod
(self,axis,rtype). Return 1-dproducts of elements inself alongaxis. Perform the productafter converting data to data typertype.
- PyObject*PyArray_CumProd(PyArrayObject*self,intaxis,intrtype,PyArrayObject*out)#
Equivalent to
ndarray.cumprod
(self,axis,rtype). Return1-d cumulative products of elements inself
alongaxis
.Perform the product after converting data to data typertype
.
- PyObject*PyArray_All(PyArrayObject*self,intaxis,PyArrayObject*out)#
Equivalent to
ndarray.all
(self,axis). Return an array withTrue elements for every 1-d sub-array ofself
defined byaxis
in which all the elements are True.
- PyObject*PyArray_Any(PyArrayObject*self,intaxis,PyArrayObject*out)#
Equivalent to
ndarray.any
(self,axis). Return an array withTrue elements for every 1-d sub-array ofself defined byaxisin which any of the elements are True.
Functions#
Array Functions#
- intPyArray_AsCArray(PyObject**op,void*ptr,npy_intp*dims,intnd,PyArray_Descr*typedescr)#
Sometimes it is useful to access a multidimensional array as aC-style multi-dimensional array so that algorithms can beimplemented using C’s a[i][j][k] syntax. This routine returns apointer,ptr, that simulates this kind of C-style array, for1-, 2-, and 3-d ndarrays.
- Parameters:
op – The address to any Python object. This Python object will be replacedwith an equivalent well-behaved, C-style contiguous, ndarray of thegiven data type specified by the last two arguments. Be sure thatstealing a reference in this way to the input object is justified.
ptr – The address to a (ctype* for 1-d, ctype** for 2-d or ctype*** for 3-d)variable where ctype is the equivalent C-type for the data type. Onreturn,ptr will be addressable as a 1-d, 2-d, or 3-d array.
dims – An output array that contains the shape of the array object. Thisarray gives boundaries on any looping that will take place.
nd – The dimensionality of the array (1, 2, or 3).
typedescr – A
PyArray_Descr
structure indicating the desired data-type(including required byteorder). The call will steal a reference tothe parameter.
Note
The simulation of a C-style array is not complete for 2-d and 3-darrays. For example, the simulated arrays of pointers cannot be passedto subroutines expecting specific, statically-defined 2-d and 3-darrays. To pass to functions requiring those kind of inputs, you muststatically define the required array and copy data.
- intPyArray_Free(PyObject*op,void*ptr)#
Must be called with the same objects and memory locations returnedfrom
PyArray_AsCArray
(…). This function cleans up memorythat otherwise would get leaked.
- PyObject*PyArray_Concatenate(PyObject*obj,intaxis)#
Join the sequence of objects inobj together alongaxis into asingle array. If the dimensions or types are not compatible anerror is raised.
- PyObject*PyArray_InnerProduct(PyObject*obj1,PyObject*obj2)#
Compute a product-sum over the last dimensions ofobj1 andobj2. Neither array is conjugated.
- PyObject*PyArray_MatrixProduct(PyObject*obj1,PyObject*obj)#
Compute a product-sum over the last dimension ofobj1 and thesecond-to-last dimension ofobj2. For 2-d arrays this is amatrix-product. Neither array is conjugated.
- PyObject*PyArray_MatrixProduct2(PyObject*obj1,PyObject*obj,PyArrayObject*out)#
Same as PyArray_MatrixProduct, but store the result inout. Theoutput array must have the correct shape, type, and beC-contiguous, or an exception is raised.
- PyArrayObject*PyArray_EinsteinSum(char*subscripts,npy_intpnop,PyArrayObject**op_in,PyArray_Descr*dtype,NPY_ORDERorder,NPY_CASTINGcasting,PyArrayObject*out)#
Applies the Einstein summation convention to the array operandsprovided, returning a new array or placing the result inout.The string insubscripts is a comma separated list of indexletters. The number of operands is innop, andop_in is anarray containing those operands. The data type of the output canbe forced withdtype, the output order can be forced withorder(
NPY_KEEPORDER
is recommended), and whendtype is specified,casting indicates how permissive the data conversion should be.See the
einsum
function for more details.
- PyObject*PyArray_Correlate(PyObject*op1,PyObject*op2,intmode)#
Compute the 1-d correlation of the 1-d arraysop1 andop2. The correlation is computed at each output point by multiplyingop1 by a shifted version ofop2 and summing the result. As aresult of the shift, needed values outside of the defined range ofop1 andop2 are interpreted as zero. The mode determines howmany shifts to return: 0 - return only shifts that did not need toassume zero- values; 1 - return an object that is the same size asop1, 2 - return all possible shifts (any overlap at all isaccepted).
Notes
This does not compute the usual correlation: if op2 is larger than op1, thearguments are swapped, and the conjugate is never taken for complex arrays.See PyArray_Correlate2 for the usual signal processing correlation.
- PyObject*PyArray_Correlate2(PyObject*op1,PyObject*op2,intmode)#
Updated version of PyArray_Correlate, which uses the usual definition ofcorrelation for 1d arrays. The correlation is computed at each output pointby multiplyingop1 by a shifted version ofop2 and summing the result.As a result of the shift, needed values outside of the defined range ofop1 andop2 are interpreted as zero. The mode determines how manyshifts to return: 0 - return only shifts that did not need to assume zero-values; 1 - return an object that is the same size asop1, 2 - return allpossible shifts (any overlap at all is accepted).
Notes
Compute z as follows:
z[k]=sum_nop1[n]*conj(op2[n+k])
Other functions#
- npy_boolPyArray_CheckStrides(intelsize,intnd,npy_intpnumbytes,npy_intpconst*dims,npy_intpconst*newstrides)#
Determine ifnewstrides is a strides array consistent with thememory of annd -dimensional array with shape
dims
andelement-size,elsize. Thenewstrides array is checked to seeif jumping by the provided number of bytes in each direction willever mean jumping more thannumbytes which is the assumed sizeof the available memory segment. Ifnumbytes is 0, then anequivalentnumbytes is computed assumingnd,dims, andelsize refer to a single-segment array. ReturnNPY_TRUE
ifnewstrides is acceptable, otherwise returnNPY_FALSE
.
- intPyArray_MultiplyIntList(intconst*seq,intn)#
Both of these routines multiply ann -length array,seq, ofintegers and return the result. No overflow checking is performed.
Auxiliary data with object semantics#
- typeNpyAuxData#
When working with more complex dtypes which are composed of other dtypes,such as the struct dtype, creating inner loops that manipulate the dtypesrequires carrying along additional data. NumPy supports this ideathrough a structNpyAuxData
, mandating a few conventions so thatit is possible to do this.
Defining anNpyAuxData
is similar to defining a class in C++,but the object semantics have to be tracked manually since the API is in C.Here’s an example for a function which doubles up an element usingan element copier function as a primitive.
typedefstruct{NpyAuxDatabase;ElementCopier_Func*func;NpyAuxData*funcdata;}eldoubler_aux_data;voidfree_element_doubler_aux_data(NpyAuxData*data){eldoubler_aux_data*d=(eldoubler_aux_data*)data;/* Free the memory owned by this auxdata */NPY_AUXDATA_FREE(d->funcdata);PyArray_free(d);}NpyAuxData*clone_element_doubler_aux_data(NpyAuxData*data){eldoubler_aux_data*ret=PyArray_malloc(sizeof(eldoubler_aux_data));if(ret==NULL){returnNULL;}/* Raw copy of all data */memcpy(ret,data,sizeof(eldoubler_aux_data));/* Fix up the owned auxdata so we have our own copy */ret->funcdata=NPY_AUXDATA_CLONE(ret->funcdata);if(ret->funcdata==NULL){PyArray_free(ret);returnNULL;}return(NpyAuxData*)ret;}NpyAuxData*create_element_doubler_aux_data(ElementCopier_Func*func,NpyAuxData*funcdata){eldoubler_aux_data*ret=PyArray_malloc(sizeof(eldoubler_aux_data));if(ret==NULL){PyErr_NoMemory();returnNULL;}memset(&ret,0,sizeof(eldoubler_aux_data));ret->base->free=&free_element_doubler_aux_data;ret->base->clone=&clone_element_doubler_aux_data;ret->func=func;ret->funcdata=funcdata;return(NpyAuxData*)ret;}
- typeNpyAuxData_FreeFunc#
The function pointer type for NpyAuxData free functions.
- typeNpyAuxData_CloneFunc#
The function pointer type for NpyAuxData clone functions. Thesefunctions should never set the Python exception on error, becausethey may be called from a multi-threaded context.
- voidNPY_AUXDATA_FREE(NpyAuxData*auxdata)#
A macro which calls the auxdata’s free function appropriately,does nothing if auxdata is NULL.
- NpyAuxData*NPY_AUXDATA_CLONE(NpyAuxData*auxdata)#
A macro which calls the auxdata’s clone function appropriately,returning a deep copy of the auxiliary data.
Array iterators#
As of NumPy 1.6.0, these array iterators are superseded bythe new array iterator,NpyIter
.
An array iterator is a simple way to access the elements of anN-dimensional array quickly and efficiently, as seen intheexample which provides more descriptionof this useful approach to looping over an array from C.
- PyObject*PyArray_IterNew(PyObject*arr)#
Return an array iterator object from the array,arr. This isequivalent toarr.flat. The array iterator object makesit easy to loop over an N-dimensional non-contiguous array inC-style contiguous fashion.
- PyObject*PyArray_IterAllButAxis(PyObject*arr,int*axis)#
Return an array iterator that will iterate over all axes but theone provided in*axis. The returned iterator cannot be usedwith
PyArray_ITER_GOTO1D
. This iterator could be used towrite something similar to what ufuncs do wherein the loop overthe largest axis is done by a separate sub-routine. If*axis isnegative then*axis will be set to the axis having the smalleststride and that axis will be used.
- PyObject*PyArray_BroadcastToShape(PyObject*arr,npy_intpconst*dimensions,intnd)#
Return an array iterator that is broadcast to iterate as an arrayof the shape provided bydimensions andnd.
- intPyArrayIter_Check(PyObject*op)#
Evaluates true ifop is an array iterator (or instance of asubclass of the array iterator type).
- voidPyArray_ITER_NEXT(PyObject*iterator)#
Increment the index and the dataptr members of theiterator topoint to the next element of the array. If the array is not(C-style) contiguous, also increment the N-dimensional coordinatesarray.
- voidPyArray_ITER_GOTO(PyObject*iterator,npy_intp*destination)#
Set theiterator index, dataptr, and coordinates members to thelocation in the array indicated by the N-dimensional c-array,destination, which must have size at leastiterator->nd_m1+1.
Broadcasting (multi-iterators)#
- PyObject*PyArray_MultiIterNew(intnum,...)#
A simplified interface to broadcasting. This function takes thenumber of arrays to broadcast and thennum extra (
PyObject*
) arguments. These arguments are converted to arrays and iteratorsare created.PyArray_Broadcast
is then called on the resultingmulti-iterator object. The resulting, broadcasted mult-iteratorobject is then returned. A broadcasted operation can then beperformed using a single loop and usingPyArray_MultiIter_NEXT
(..)
- voidPyArray_MultiIter_RESET(PyObject*multi)#
Reset all the iterators to the beginning in a multi-iteratorobject,multi.
- voidPyArray_MultiIter_NEXT(PyObject*multi)#
Advance each iterator in a multi-iterator object,multi, to itsnext (broadcasted) element.
- void*PyArray_MultiIter_DATA(PyObject*multi,inti)#
Return the data-pointer of thei\(^{\textrm{th}}\) iteratorin a multi-iterator object.
- voidPyArray_MultiIter_NEXTi(PyObject*multi,inti)#
Advance the pointer of only thei\(^{\textrm{th}}\) iterator.
- voidPyArray_MultiIter_GOTO(PyObject*multi,npy_intp*destination)#
Advance each iterator in a multi-iterator object,multi, to thegiven\(N\) -dimensionaldestination where\(N\) is thenumber of dimensions in the broadcasted array.
- voidPyArray_MultiIter_GOTO1D(PyObject*multi,npy_intpindex)#
Advance each iterator in a multi-iterator object,multi, to thecorresponding location of theindex into the flattenedbroadcasted array.
- intPyArray_MultiIter_NOTDONE(PyObject*multi)#
Evaluates TRUE as long as the multi-iterator has not loopedthrough all of the elements (of the broadcasted result), otherwiseit evaluates FALSE.
- npy_intpPyArray_MultiIter_SIZE(PyArrayMultiIterObject*multi)#
New in version 1.26.0.
Returns the total broadcasted size of a multi-iterator object.
- intPyArray_MultiIter_NDIM(PyArrayMultiIterObject*multi)#
New in version 1.26.0.
Returns the number of dimensions in the broadcasted result ofa multi-iterator object.
- npy_intpPyArray_MultiIter_INDEX(PyArrayMultiIterObject*multi)#
New in version 1.26.0.
Returns the current (1-d) index into the broadcasted resultof a multi-iterator object.
- intPyArray_MultiIter_NUMITER(PyArrayMultiIterObject*multi)#
New in version 1.26.0.
Returns the number of iterators that are represented by amulti-iterator object.
- void**PyArray_MultiIter_ITERS(PyArrayMultiIterObject*multi)#
New in version 1.26.0.
Returns an array of iterator objects that holds the iterators for thearrays to be broadcast together. On return, the iterators are adjustedfor broadcasting.
- npy_intp*PyArray_MultiIter_DIMS(PyArrayMultiIterObject*multi)#
New in version 1.26.0.
Returns a pointer to the dimensions/shape of the broadcasted result of amulti-iterator object.
- intPyArray_Broadcast(PyArrayMultiIterObject*mit)#
This function encapsulates the broadcasting rules. Themitcontainer should already contain iterators for all the arrays thatneed to be broadcast. On return, these iterators will be adjustedso that iteration over each simultaneously will accomplish thebroadcasting. A negative number is returned if an error occurs.
- intPyArray_RemoveSmallest(PyArrayMultiIterObject*mit)#
This function takes a multi-iterator object that has beenpreviously “broadcasted,” finds the dimension with the smallest“sum of strides” in the broadcasted result and adapts all theiterators so as not to iterate over that dimension (by effectivelymaking them of length-1 in that dimension). The correspondingdimension is returned unlessmit ->nd is 0, then -1 isreturned. This function is useful for constructing ufunc-likeroutines that broadcast their inputs correctly and then call astrided 1-d version of the routine as the inner-loop. This 1-dversion is usually optimized for speed and for this reason theloop should be performed over the axis that won’t require largestride jumps.
Neighborhood iterator#
Neighborhood iterators are subclasses of the iterator object, and can be usedto iter over a neighborhood of a point. For example, you may want to iterateover every voxel of a 3d image, and for every such voxel, iterate over anhypercube. Neighborhood iterator automatically handle boundaries, thus makingthis kind of code much easier to write than manual boundaries handling, at thecost of a slight overhead.
- PyObject*PyArray_NeighborhoodIterNew(PyArrayIterObject*iter,npy_intpbounds,intmode,PyArrayObject*fill_value)#
This function creates a new neighborhood iterator from an existingiterator. The neighborhood will be computed relatively to the positioncurrently pointed byiter, the bounds define the shape of theneighborhood iterator, and the mode argument the boundaries handling mode.
Thebounds argument is expected to be a (2 * iter->ao->nd) arrays, suchas the range bound[2*i]->bounds[2*i+1] defines the range where to walk fordimension i (both bounds are included in the walked coordinates). Thebounds should be ordered for each dimension (bounds[2*i] <= bounds[2*i+1]).
The mode should be one of:
- NPY_NEIGHBORHOOD_ITER_ZERO_PADDING#
Zero padding. Outside bounds values will be 0.
- NPY_NEIGHBORHOOD_ITER_ONE_PADDING#
One padding, Outside bounds values will be 1.
- NPY_NEIGHBORHOOD_ITER_CONSTANT_PADDING#
Constant padding. Outside bounds values will be thesame as the first item in fill_value.
- NPY_NEIGHBORHOOD_ITER_MIRROR_PADDING#
Mirror padding. Outside bounds values will be as if thearray items were mirrored. For example, for the array [1, 2, 3, 4],x[-2] will be 2, x[-2] will be 1, x[4] will be 4, x[5] will be 1,etc…
- NPY_NEIGHBORHOOD_ITER_CIRCULAR_PADDING#
Circular padding. Outside bounds values will be as if the arraywas repeated. For example, for the array [1, 2, 3, 4], x[-2] willbe 3, x[-2] will be 4, x[4] will be 1, x[5] will be 2, etc…
If the mode is constant filling (
NPY_NEIGHBORHOOD_ITER_CONSTANT_PADDING
),fill_value should point to an array object which holds the filling value(the first item will be the filling value if the array contains more thanone item). For other cases, fill_value may be NULL.The iterator holds a reference to iter
Return NULL on failure (in which case the reference count of iter is notchanged)
iter itself can be a Neighborhood iterator: this can be useful for .e.gautomatic boundaries handling
the object returned by this function should be safe to use as a normaliterator
If the position of iter is changed, any subsequent call toPyArrayNeighborhoodIter_Next is undefined behavior, andPyArrayNeighborhoodIter_Reset must be called.
If the position of iter is not the beginning of the data and theunderlying data for iter is contiguous, the iterator will point to thestart of the data instead of position pointed by iter.To avoid this situation, iter should be moved to the required positiononly after the creation of iterator, and PyArrayNeighborhoodIter_Resetmust be called.
PyArrayIterObject*iter;PyArrayNeighborhoodIterObject*neigh_iter;iter=PyArray_IterNew(x);/*For a 3x3 kernel */bounds={-1,1,-1,1};neigh_iter=(PyArrayNeighborhoodIterObject*)PyArray_NeighborhoodIterNew(iter,bounds,NPY_NEIGHBORHOOD_ITER_ZERO_PADDING,NULL);for(i=0;i<iter->size;++i){for(j=0;j<neigh_iter->size;++j){/* Walk around the item currently pointed by iter->dataptr */PyArrayNeighborhoodIter_Next(neigh_iter);}/* Move to the next point of iter */PyArrayIter_Next(iter);PyArrayNeighborhoodIter_Reset(neigh_iter);}
- NPY_NEIGHBORHOOD_ITER_ZERO_PADDING#
- intPyArrayNeighborhoodIter_Reset(PyArrayNeighborhoodIterObject*iter)#
Reset the iterator position to the first point of the neighborhood. Thisshould be called whenever the iter argument given atPyArray_NeighborhoodIterObject is changed (see example)
- intPyArrayNeighborhoodIter_Next(PyArrayNeighborhoodIterObject*iter)#
After this call, iter->dataptr points to the next point of theneighborhood. Calling this function after every point of theneighborhood has been visited is undefined.
Array scalars#
- PyObject*PyArray_Return(PyArrayObject*arr)#
This function steals a reference toarr.
This function checks to see ifarr is a 0-dimensional array and,if so, returns the appropriate array scalar. It should be usedwhenever 0-dimensional arrays could be returned to Python.
- PyObject*PyArray_Scalar(void*data,PyArray_Descr*dtype,PyObject*base)#
Return an array scalar object of the givendtype bycopyingfrom memory pointed to bydata.base is expected to be thearray object that is the owner of the data.base is requiredifdtype is a
void
scalar, or if theNPY_USE_GETITEM
flag is set and it is known that thegetitem
method usesthearr
argument without checking if it isNULL
. Otherwisebase may beNULL
.If the data is not in native byte order (as indicated by
dtype->byteorder
) then this function will byteswap the data,because array scalars are always in correct machine-byte order.
- PyObject*PyArray_ToScalar(void*data,PyArrayObject*arr)#
Return an array scalar object of the type and itemsize indicatedby the array objectarr copied from the memory pointed to bydata and swapping if the data inarr is not in machinebyte-order.
- PyObject*PyArray_FromScalar(PyObject*scalar,PyArray_Descr*outcode)#
Return a 0-dimensional array of type determined byoutcode fromscalar which should be an array-scalar object. Ifoutcode isNULL, then the type is determined fromscalar.
- voidPyArray_ScalarAsCtype(PyObject*scalar,void*ctypeptr)#
Return inctypeptr a pointer to the actual value in an arrayscalar. There is no error checking soscalar must be anarray-scalar object, and ctypeptr must have enough space to holdthe correct type. For flexible-sized types, a pointer to the datais copied into the memory ofctypeptr, for all other types, theactual data is copied into the address pointed to byctypeptr.
- intPyArray_CastScalarToCtype(PyObject*scalar,void*ctypeptr,PyArray_Descr*outcode)#
Return the data (cast to the data type indicated byoutcode)from the array-scalar,scalar, into the memory pointed to byctypeptr (which must be large enough to handle the incomingmemory).
Returns -1 on failure, and 0 on success.
- PyObject*PyArray_TypeObjectFromType(inttype)#
Returns a scalar type-object from a type-number,type. Equivalent to
PyArray_DescrFromType
(type)->typeobjexcept for reference counting and error-checking. Returns a newreference to the typeobject on success orNULL
on failure.
- NPY_SCALARKINDPyArray_ScalarKind(inttypenum,PyArrayObject**arr)#
Legacy way to query special promotion for scalar values. This is notused in NumPy itself anymore and is expected to be deprecated eventually.
New DTypes can define promotion rules specific to Python scalars.
- intPyArray_CanCoerceScalar(charthistype,charneededtype,NPY_SCALARKINDscalar)#
Legacy way to query special promotion for scalar values. This is notused in NumPy itself anymore and is expected to be deprecated eventually.
Use
PyArray_ResultType
for similar purposes.
Data-type descriptors#
Warning
Data-type objects must be reference counted so be aware of theaction on the data-type reference of different C-API calls. Thestandard rule is that when a data-type object is returned it is anew reference. Functions that takePyArray_Descr* objects andreturn arrays steal references to the data-type their inputsunless otherwise noted. Therefore, you must own a reference to anydata-type object used as input to such a function.
- intPyArray_DescrCheck(PyObject*obj)#
Evaluates as true ifobj is a data-type object (PyArray_Descr* ).
- PyArray_Descr*PyArray_DescrNew(PyArray_Descr*obj)#
Return a new data-type object copied fromobj (the fieldsreference is just updated so that the new object points to thesame fields dictionary if any).
- PyArray_Descr*PyArray_DescrNewFromType(inttypenum)#
Create a new data-type object from the built-in (oruser-registered) data-type indicated bytypenum. All builtintypes should not have any of their fields changed. This creates anew copy of the
PyArray_Descr
structure so that you can fillit in as appropriate. This function is especially needed forflexible data-types which need to have a new elsize member inorder to be meaningful in array construction.
- PyArray_Descr*PyArray_DescrNewByteorder(PyArray_Descr*obj,charnewendian)#
Create a new data-type object with the byteorder set according tonewendian. All referenced data-type objects (in subdescr andfields members of the data-type object) are also changed(recursively).
The value ofnewendian is one of these macros:
- NPY_IGNORE#
- NPY_SWAP#
- NPY_NATIVE#
- NPY_LITTLE#
- NPY_BIG#
If a byteorder of
NPY_IGNORE
is encountered itis left alone. If newendian isNPY_SWAP
, then all byte-ordersare swapped. Other valid newendian values areNPY_NATIVE
,NPY_LITTLE
, andNPY_BIG
which all causethe returned data-typed descriptor (and all it’sreferenced data-type descriptors) to have the corresponding byte-order.
- PyArray_Descr*PyArray_DescrFromObject(PyObject*op,PyArray_Descr*mintype)#
Determine an appropriate data-type object from the objectop(which should be a “nested” sequence object) and the minimumdata-type descriptor mintype (which can be
NULL
). Similar inbehavior to array(op).dtype. Don’t confuse this function withPyArray_DescrConverter
. This function essentially looks atall the objects in the (nested) sequence and determines thedata-type from the elements it finds.
- PyArray_Descr*PyArray_DescrFromScalar(PyObject*scalar)#
Return a data-type object from an array-scalar object. No checkingis done to be sure thatscalar is an array scalar. If nosuitable data-type can be determined, then a data-type of
NPY_OBJECT
is returned by default.
- PyArray_Descr*PyArray_DescrFromType(inttypenum)#
Returns a data-type object corresponding totypenum. Thetypenum can be one of the enumerated types, a character code forone of the enumerated types, or a user-defined type. If you want to use aflexible size array, then you need to
flexibletypenum
and set theresultselsize
parameter to the desired size. The typenum is one of theNPY_TYPES
.
- intPyArray_DescrConverter(PyObject*obj,PyArray_Descr**dtype)#
Convert any compatible Python object,obj, to a data-type objectindtype. A large number of Python objects can be converted todata-type objects. SeeData type objects (dtype) for a completedescription. This version of the converter converts None objectsto a
NPY_DEFAULT_TYPE
data-type object. This function canbe used with the “O&” character code inPyArg_ParseTuple
processing.
- intPyArray_DescrConverter2(PyObject*obj,PyArray_Descr**dtype)#
Convert any compatible Python object,obj, to a data-typeobject indtype. This version of the converter converts Noneobjects so that the returned data-type is
NULL
. This functioncan also be used with the “O&” character in PyArg_ParseTupleprocessing.
- intPyArray_DescrAlignConverter(PyObject*obj,PyArray_Descr**dtype)#
Like
PyArray_DescrConverter
except it aligns C-struct-likeobjects on word-boundaries as the compiler would.
- intPyArray_DescrAlignConverter2(PyObject*obj,PyArray_Descr**dtype)#
Like
PyArray_DescrConverter2
except it aligns C-struct-likeobjects on word-boundaries as the compiler would.
Data Type Promotion and Inspection#
- PyArray_DTypeMeta*PyArray_CommonDType(constPyArray_DTypeMeta*dtype1,constPyArray_DTypeMeta*dtype2)#
This function defines the common DType operator. Note that the common DTypewill not be
object
(unless one of the DTypes isobject
). Similar tonumpy.result_type
, but works on the classes and not instances.
- PyArray_DTypeMeta*PyArray_PromoteDTypeSequence(npy_intplength,PyArray_DTypeMeta**dtypes_in)#
Promotes a list of DTypes with each other in a way that should guaranteestable results even when changing the order. This function is smarter andcan often return successful and unambiguous results when
common_dtype(common_dtype(dt1,dt2),dt3)
would depend on the operationorder or fail. Nevertheless, DTypes should aim to ensure that theircommon-dtype implementation is associative and commutative! (Mainly,unsigned and signed integers are not.)For guaranteed consistent results DTypes must implement common-Dtype“transitively”. If A promotes B and B promotes C, than A must generallyalso promote C; where “promotes” means implements the promotion. (Thereare some exceptions for abstract DTypes)
In general this approach always works as long as the most generic dtypeis either strictly larger, or compatible with all other dtypes.For example promoting
float16
with any other float, integer, or unsignedinteger again gives a floating point number.
- PyArray_Descr*PyArray_GetDefaultDescr(constPyArray_DTypeMeta*DType)#
Given a DType class, returns the default instance (descriptor). This checksfor a
singleton
first and only calls thedefault_descr
function ifnecessary.
Custom Data Types#
New in version 2.0.
These functions allow defining custom flexible data types outside of NumPy. SeeNEP 42 for more details about the rationale and design of the newDType system. See thenumpy-user-dtypes repository for a number of example DTypes.Also seePyArray_DTypeMeta and PyArrayDTypeMeta_Spec for documentation onPyArray_DTypeMeta
andPyArrayDTypeMeta_Spec
.
- intPyArrayInitDTypeMeta_FromSpec(PyArray_DTypeMeta*Dtype,PyArrayDTypeMeta_Spec*spec)#
Initialize a new DType. It must currently be a static Python C type that isdeclared as
PyArray_DTypeMeta
and notPyTypeObject
.Further, it must subclassnp.dtype and set its type toPyArrayDTypeMeta_Type
(before callingPyType_Ready
),which has additional fields compared to a normalPyTypeObject
. Seethe examples in thenumpy-user-dtypes
repository for usage with bothparametric and non-parametric data types.
Flags#
Flags that can be set on thePyArrayDTypeMeta_Spec
to initialize the DType.
- NPY_DT_ABSTRACT#
Indicates the DType is an abstract “base” DType in a DType hierarchy andshould not be directly instantiated.
- NPY_DT_PARAMETRIC#
Indicates the DType is parametric and does not have a unique singletoninstance.
- NPY_DT_NUMERIC#
Indicates the DType represents a numerical value.
Slot IDs and API Function Typedefs#
These IDs correspond to slots in the DType API and are used to identifyimplementations of each slot from the items of theslots
arraymember ofPyArrayDTypeMeta_Spec
struct.
- NPY_DT_discover_descr_from_pyobject#
- typedefPyArray_Descr*(PyArrayDTypeMeta_DiscoverDescrFromPyobject)(PyArray_DTypeMeta*cls,PyObject*obj)#
Used during DType inference to find the correct DType for a givenPyObject. Must return a descriptor instance appropriate to store thedata in the python object that is passed in.obj is the python objectto inspect andcls is the DType class to create a descriptor for.
- NPY_DT_default_descr#
- typedefPyArray_Descr*(PyArrayDTypeMeta_DefaultDescriptor)(PyArray_DTypeMeta*cls)#
Returns the default descriptor instance for the DType. Must bedefined for parametric data types. Non-parametric data types returnthe singleton by default.
- NPY_DT_common_dtype#
- typedefPyArray_DTypeMeta*(PyArrayDTypeMeta_CommonDType)(PyArray_DTypeMeta*dtype1,PyArray_DTypeMeta*dtype2)#
Given two input DTypes, determines the appropriate “common” DTypethat can store values for both types. Returns
Py_NotImplemented
if no such type exists.
- NPY_DT_common_instance#
- typedefPyArray_Descr*(PyArrayDTypeMeta_CommonInstance)(PyArray_Descr*dtype1,PyArray_Descr*dtype2)#
Given two input descriptors, determines the appropriate “common”descriptor that can store values for both instances. Returns
NULL
on error.
- NPY_DT_ensure_canonical#
- typedefPyArray_Descr*(PyArrayDTypeMeta_EnsureCanonical)(PyArray_Descr*dtype)#
Returns the “canonical” representation for a descriptor instance. Thenotion of a canonical descriptor generalizes the concept of byteorder, in that a canonical descriptor always has native byteorder. If the descriptor is already canonical, this function returnsa new reference to the input descriptor.
- NPY_DT_setitem#
- typedefint(PyArrayDTypeMeta_SetItem)(PyArray_Descr*,PyObject*,char*)#
Implements scalar setitem for an array element given a PyObject.
- NPY_DT_getitem#
- typedefPyObject*(PyArrayDTypeMeta_GetItem)(PyArray_Descr*,char*)#
Implements scalar getitem for an array element. Must return a pythonscalar.
- NPY_DT_get_clear_loop#
If defined, sets a traversal loop that clears data in the array. Thisis most useful for arrays of references that must clean up arrayentries before the array is garbage collected. Implements
PyArrayMethod_GetTraverseLoop
.
- NPY_DT_get_fill_zero_loop#
If defined, sets a traversal loop that fills an array with “zero”values, which may have a DType-specific meaning. This is calledinside
numpy.zeros
for arrays that need to write a custom sentinelvalue that represents zero if for some reason a zero-filled array isnot sufficient. ImplementsPyArrayMethod_GetTraverseLoop
.
- NPY_DT_finalize_descr#
- typedefPyArray_Descr*(PyArrayDTypeMeta_FinalizeDescriptor)(PyArray_Descr*dtype)#
If defined, a function that is called to “finalize” a descriptorinstance after an array is created. One use of this function is toforce newly created arrays to have a newly created descriptorinstance, no matter what input descriptor is provided by a user.
PyArray_ArrFuncs slots#
In addition the above slots, the following slots are exposed to allowfilling thePyArray_ArrFuncs struct attached to descriptorinstances. Note that in the future these will be replaced by properDType API slots but for now we have exposed the legacyPyArray_ArrFuncs
slots.
- NPY_DT_PyArray_ArrFuncs_getitem#
Allows setting a per-dtype getitem. Note that this is not necessaryto define unless the default version calling the function definedwith the
NPY_DT_getitem
ID is unsuitable. This version will be slightlyfaster than usingNPY_DT_getitem
at the cost of sometimes needing to dealwith a NULL input array.
- NPY_DT_PyArray_ArrFuncs_setitem#
Allows setting a per-dtype setitem. Note that this is not necessaryto define unless the default version calling the function definedwith the
NPY_DT_setitem
ID is unsuitable for some reason.
- NPY_DT_PyArray_ArrFuncs_compare#
Computes a comparison for
numpy.sort
, implementsPyArray_CompareFunc
.
- NPY_DT_PyArray_ArrFuncs_argmax#
Computes the argmax for
numpy.argmax
, implementsPyArray_ArgFunc
.
- NPY_DT_PyArray_ArrFuncs_argmin#
Computes the argmin for
numpy.argmin
, implementsPyArray_ArgFunc
.
- NPY_DT_PyArray_ArrFuncs_scanfunc#
A formatted input function for
numpy.fromfile
, implementsPyArray_ScanFunc
.
- NPY_DT_PyArray_ArrFuncs_fromstr#
A string parsing function for
numpy.fromstring
, implementsPyArray_FromStrFunc
.
- NPY_DT_PyArray_ArrFuncs_nonzero#
Computes the nonzero function for
numpy.nonzero
, implementsPyArray_NonzeroFunc
.
- NPY_DT_PyArray_ArrFuncs_fill#
An array filling function for
numpy.ndarray.fill
, implementsPyArray_FillFunc
.
- NPY_DT_PyArray_ArrFuncs_fillwithscalar#
A function to fill an array with a scalar value for
numpy.ndarray.fill
,implementsPyArray_FillWithScalarFunc
.
- NPY_DT_PyArray_ArrFuncs_sort#
An array of PyArray_SortFunc of length
NPY_NSORTS
. If set, allowsdefining custom sorting implementations for each of the sortingalgorithms numpy implements.
- NPY_DT_PyArray_ArrFuncs_argsort#
An array of PyArray_ArgSortFunc of length
NPY_NSORTS
. If set,allows defining custom argsorting implementations for each of thesorting algorithms numpy implements.
Macros and Static Inline Functions#
These macros and static inline functions are provided to allow moreunderstandable and idiomatic code when working withPyArray_DTypeMeta
instances.
- NPY_DTYPE(descr)#
Returns a
PyArray_DTypeMeta*
pointer to the DType of a givendescriptor instance.
- staticinlinePyArray_DTypeMeta*NPY_DT_NewRef(PyArray_DTypeMeta*o)#
Returns a
PyArray_DTypeMeta*
pointer to a new reference to aDType.
Conversion utilities#
For use withPyArg_ParseTuple
#
All of these functions can be used inPyArg_ParseTuple
(…) withthe “O&” format specifier to automatically convert any Python objectto the required C-object. All of these functions returnNPY_SUCCEED
if successful andNPY_FAIL
if not. The firstargument to all of these function is a Python object. The secondargument is theaddress of the C-type to convert the Python objectto.
Warning
Be sure to understand what steps you should take to manage thememory when using these conversion functions. These functions canrequire freeing memory, and/or altering the reference counts ofspecific objects based on your use.
- intPyArray_Converter(PyObject*obj,PyObject**address)#
Convert any Python object to a
PyArrayObject
. IfPyArray_Check
(obj) is TRUE then its reference count isincremented and a reference placed inaddress. Ifobj is notan array, then convert it to an array usingPyArray_FromAny
. No matter what is returned, you must DECREF the object returnedby this routine inaddress when you are done with it.
- intPyArray_OutputConverter(PyObject*obj,PyArrayObject**address)#
This is a default converter for output arrays given tofunctions. Ifobj is
Py_None
orNULL
, then*addresswill beNULL
but the call will succeed. IfPyArray_Check
(obj) is TRUE then it is returned in*address withoutincrementing its reference count.
- intPyArray_IntpConverter(PyObject*obj,PyArray_Dims*seq)#
Convert any Python sequence,obj, smaller than
NPY_MAXDIMS
to a C-array ofnpy_intp
. The Python object could also be asingle number. Theseq variable is a pointer to a structure withmembers ptr and len. On successful return,seq ->ptr contains apointer to memory that must be freed, by callingPyDimMem_FREE
,to avoid a memory leak. The restriction on memory size allows thisconverter to be conveniently used for sequences intended to beinterpreted as array shapes.
- intPyArray_BufferConverter(PyObject*obj,PyArray_Chunk*buf)#
Convert any Python object,obj, with a (single-segment) bufferinterface to a variable with members that detail the object’s useof its chunk of memory. Thebuf variable is a pointer to astructure with base, ptr, len, and flags members. The
PyArray_Chunk
structure is binary compatible with thePython’s buffer object (through its len member on 32-bit platformsand its ptr member on 64-bit platforms). On return, the base memberis set toobj (or its base ifobj is already a buffer objectpointing to another object). If you need to hold on to the memorybe sure to INCREF the base member. The chunk of memory is pointedto bybuf ->ptr member and has lengthbuf ->len. The flagsmember ofbuf isNPY_ARRAY_ALIGNED
with theNPY_ARRAY_WRITEABLE
flag set ifobj has a writeablebuffer interface.
- intPyArray_AxisConverter(PyObject*obj,int*axis)#
Convert a Python object,obj, representing an axis argument tothe proper value for passing to the functions that take an integeraxis. Specifically, ifobj is None,axis is set to
NPY_RAVEL_AXIS
which is interpreted correctly by the C-APIfunctions that take axis arguments.
- intPyArray_BoolConverter(PyObject*obj,npy_bool*value)#
Convert any Python object,obj, to
NPY_TRUE
orNPY_FALSE
, and place the result invalue.
- intPyArray_ByteorderConverter(PyObject*obj,char*endian)#
Convert Python strings into the corresponding byte-ordercharacter:‘>’, ‘<’, ‘s’, ‘=’, or ‘|’.
- intPyArray_SortkindConverter(PyObject*obj,NPY_SORTKIND*sort)#
Convert Python strings into one of
NPY_QUICKSORT
(startswith ‘q’ or ‘Q’),NPY_HEAPSORT
(starts with ‘h’ or ‘H’),NPY_MERGESORT
(starts with ‘m’ or ‘M’) orNPY_STABLESORT
(starts with ‘t’ or ‘T’).NPY_MERGESORT
andNPY_STABLESORT
are aliased to each other for backwards compatibility and may refer to oneof several stable sorting algorithms depending on the data type.
- intPyArray_SearchsideConverter(PyObject*obj,NPY_SEARCHSIDE*side)#
Convert Python strings into one of
NPY_SEARCHLEFT
(starts with ‘l’or ‘L’), orNPY_SEARCHRIGHT
(starts with ‘r’ or ‘R’).
- intPyArray_OrderConverter(PyObject*obj,NPY_ORDER*order)#
Convert the Python strings ‘C’, ‘F’, ‘A’, and ‘K’ into the
NPY_ORDER
enumerationNPY_CORDER
,NPY_FORTRANORDER
,NPY_ANYORDER
, andNPY_KEEPORDER
.
- intPyArray_CastingConverter(PyObject*obj,NPY_CASTING*casting)#
Convert the Python strings ‘no’, ‘equiv’, ‘safe’, ‘same_kind’, and‘unsafe’ into the
NPY_CASTING
enumerationNPY_NO_CASTING
,NPY_EQUIV_CASTING
,NPY_SAFE_CASTING
,NPY_SAME_KIND_CASTING
, andNPY_UNSAFE_CASTING
.
- intPyArray_ClipmodeConverter(PyObject*object,NPY_CLIPMODE*val)#
Convert the Python strings ‘clip’, ‘wrap’, and ‘raise’ into the
NPY_CLIPMODE
enumerationNPY_CLIP
,NPY_WRAP
,andNPY_RAISE
.
- intPyArray_ConvertClipmodeSequence(PyObject*object,NPY_CLIPMODE*modes,intn)#
Converts either a sequence of clipmodes or a single clipmode intoa C array of
NPY_CLIPMODE
values. The number of clipmodesnmust be known before calling this function. This function is providedto help functions allow a different clipmode for each dimension.
Other conversions#
- intPyArray_PyIntAsInt(PyObject*op)#
Convert all kinds of Python objects (including arrays and arrayscalars) to a standard integer. On error, -1 is returned and anexception set. You may find useful the macro:
#define error_converting(x) (((x) == -1) && PyErr_Occurred())
Including and importing the C API#
To use the NumPy C-API you typically need to include thenumpy/ndarrayobject.h
header andnumpy/ufuncobject.h
for some ufuncrelated functionality (arrayobject.h
is an alias forndarrayobject.h
).
These two headers export most relevant functionality. In general any projectwhich uses the NumPy API must import NumPy using one of the functionsPyArray_ImportNumPyAPI()
orimport_array()
.In some places, functionality which requiresimport_array()
is notneeded, because you only need type definitions. In this case, it issufficient to includenumpy/ndarratypes.h
.
For the typical Python project, multiple C or C++ files will be compiled intoa single shared object (the Python C-module) andPyArray_ImportNumPyAPI()
should be called inside it’s module initialization.
When you have a single C-file, this will consist of:
#include"numpy/ndarrayobject.h"PyMODINIT_FUNCPyInit_my_module(void){if(PyArray_ImportNumPyAPI()<0){returnNULL;}/* Other initialization code. */}
However, most projects will have additional C files which are alllinked together into a single Python module.In this case, the helper C files typically do not have a canonical placewherePyArray_ImportNumPyAPI
should be called (although it is OK andfast to call it often).
To solve this, NumPy provides the following pattern that the the mainfile is modified to definePY_ARRAY_UNIQUE_SYMBOL
before the include:
/* Main module file */#define PY_ARRAY_UNIQUE_SYMBOL MyModule#include"numpy/ndarrayobject.h"PyMODINIT_FUNCPyInit_my_module(void){if(PyArray_ImportNumPyAPI()<0){returnNULL;}/* Other initialization code. */}
while the other files use:
/* Second file without any import */#define NO_IMPORT_ARRAY#define PY_ARRAY_UNIQUE_SYMBOL MyModule#include"numpy/ndarrayobject.h"
You can of course add the defines to a local header used throughout.You just have to make sure that the main file does _not_ defineNO_IMPORT_ARRAY
.
Fornumpy/ufuncobject.h
the same logic applies, but the unique symbolmechanism is#definePY_UFUNC_UNIQUE_SYMBOL
(both can match).
Additionally, you will probably wish to add a#defineNPY_NO_DEPRECATED_APINPY_1_7_API_VERSION
to avoid warnings about possible use of old API.
Note
If you are experiencing access violations make sure that the NumPy APIwas properly imported and the symbolPyArray_API
is notNULL
.When in a debugger, this symbols actual name will bePY_ARRAY_UNIQUE_SYMBOL``+``PyArray_API
, so for exampleMyModulePyArray_API
in the above.(E.g. even aprintf("%p\n",PyArray_API);
just before the crash.)
Mechanism details and dynamic linking#
The main part of the mechanism is that without NumPy needs to defineavoid**PyArray_API
table for you to look up all functions.Depending on your macro setup, this takes different routes depending onwhetherNO_IMPORT_ARRAY
andPY_ARRAY_UNIQUE_SYMBOL
are defined:
If neither is defined, the C-API is declared to
staticvoid**PyArray_API
, so it is only visible within thecompilation unit/file using#include<numpy/arrayobject.h>
.If only
PY_ARRAY_UNIQUE_SYMBOL
is defined (it could be empty) thenthe it is declared to a non-staticvoid**
allowing it to be usedby other files which are linked.If
NO_IMPORT_ARRAY
is defined, the table is declared asexternvoid**
, meaning that it must be linked to a file which does notuseNO_IMPORT_ARRAY
.
ThePY_ARRAY_UNIQUE_SYMBOL
mechanism additionally mangles the names toavoid conflicts.
Changed in version NumPy:2.1 changed the headers to avoid sharing the table outside of asingle shared object/dll (this was always the case on Windows).Please seeNPY_API_SYMBOL_ATTRIBUTE
for details.
In order to make use of the C-API from another extension module, theimport_array
function must be called. If the extension module isself-contained in a single .c file, then that is all that needs to bedone. If, however, the extension module involves multiple files wherethe C-API is needed then some additional steps must be taken.
- intPyArray_ImportNumPyAPI(void)#
Ensures that the NumPy C-API is imported and usable. It returns
0
on success and-1
with an error set if NumPy couldn’t be imported.While preferable to call it once at module initialization, this functionis very light-weight if called multiple times.New in version 2.0:This function is backported in the
npy_2_compat.h
header.
- import_array(void)#
This function must be called in the initialization section of amodule that will make use of the C-API. It imports the modulewhere the function-pointer table is stored and points the correctvariable to it.This macro includes a
returnNULL;
on error, so thatPyArray_ImportNumPyAPI()
is preferable for custom error checking.You may also see use of_import_array()
(a function, nota macro, but you may want to raise a better error if it fails) andthe variationsimport_array1(ret)
which customizes the return value.
- PY_ARRAY_UNIQUE_SYMBOL#
- NPY_API_SYMBOL_ATTRIBUTE#
New in version 2.1.
An additional symbol which can be used to share e.g. visibility beyondshared object boundaries.By default, NumPy adds the C visibility hidden attribute (if available):
void__attribute__((visibility("hidden")))**PyArray_API;
.You can change this by definingNPY_API_SYMBOL_ATTRIBUTE
, which willmake this:voidNPY_API_SYMBOL_ATTRIBUTE**PyArray_API;
(with additionalname mangling via the unique symbol).Adding an empty
#defineNPY_API_SYMBOL_ATTRIBUTE
will have the samebehavior as NumPy 1.x.Note
Windows never had shared visibility although you can use this macroto achieve it. We generally discourage sharing beyond shared boundarylines since importing the array API includes NumPy version checks.
- NO_IMPORT_ARRAY#
Defining
NO_IMPORT_ARRAY
before thendarrayobject.h
includeindicates that the NumPy C API import is handled in a different fileand the include mechanism will not be added here.You must have one file withoutNO_IMPORT_ARRAY
defined.#define PY_ARRAY_UNIQUE_SYMBOL cool_ARRAY_API#include<numpy/arrayobject.h>
On the other hand, coolhelper.c would contain at the top:
#define NO_IMPORT_ARRAY#define PY_ARRAY_UNIQUE_SYMBOL cool_ARRAY_API#include<numpy/arrayobject.h>
You can also put the common two last lines into an extension-localheader file as long as you make sure that NO_IMPORT_ARRAY is#defined before #including that file.
Internally, these #defines work as follows:
If neither is defined, the C-API is declared to be
staticvoid**
, so it is only visible within thecompilation unit that #includes numpy/arrayobject.h.If
PY_ARRAY_UNIQUE_SYMBOL
is #defined, butNO_IMPORT_ARRAY
is not, the C-API is declared tobevoid**
, so that it will also be visible to othercompilation units.If
NO_IMPORT_ARRAY
is #defined, regardless ofwhetherPY_ARRAY_UNIQUE_SYMBOL
is, the C-API isdeclared to beexternvoid**
, so it is expected tobe defined in another compilation unit.Whenever
PY_ARRAY_UNIQUE_SYMBOL
is #defined, italso changes the name of the variable holding the C-API, whichdefaults toPyArray_API
, to whatever the macro is#defined to.
Checking the API Version#
Because python extensions are not used in the same way as usual libraries onmost platforms, some errors cannot be automatically detected at build time oreven runtime. For example, if you build an extension using a function availableonly for numpy >= 1.3.0, and you import the extension later with numpy 1.2, youwill not get an import error (but almost certainly a segmentation fault whencalling the function). That’s why several functions are provided to check fornumpy versions. The macrosNPY_VERSION
andNPY_FEATURE_VERSION
corresponds to the numpy version used to build theextension, whereas the versions returned by the functionsPyArray_GetNDArrayCVersion
andPyArray_GetNDArrayCFeatureVersion
corresponds to the runtime numpy’s version.
The rules for ABI and API compatibilities can be summarized as follows:
Whenever
NPY_VERSION
!=PyArray_GetNDArrayCVersion()
, theextension has to be recompiled (ABI incompatibility).NPY_VERSION
==PyArray_GetNDArrayCVersion()
andNPY_FEATURE_VERSION
<=PyArray_GetNDArrayCFeatureVersion()
meansbackward compatible changes.
ABI incompatibility is automatically detected in every numpy’s version. APIincompatibility detection was added in numpy 1.4.0. If you want to supportedmany different numpy versions with one extension binary, you have to build yourextension with the lowestNPY_FEATURE_VERSION
as possible.
- NPY_VERSION#
The current version of the ndarray object (check to see if thisvariable is defined to guarantee the
numpy/arrayobject.h
header isbeing used).
- NPY_FEATURE_VERSION#
The current version of the C-API.
- unsignedintPyArray_GetNDArrayCVersion(void)#
This just returns the value
NPY_VERSION
.NPY_VERSION
changes whenever a backward incompatible change at the ABI level. Becauseit is in the C-API, however, comparing the output of this function from thevalue defined in the current header gives a way to test if the C-API haschanged thus requiring a re-compilation of extension modules that use theC-API. This is automatically checked in the functionimport_array
.
- unsignedintPyArray_GetNDArrayCFeatureVersion(void)#
This just returns the value
NPY_FEATURE_VERSION
.NPY_FEATURE_VERSION
changes whenever the API changes (e.g. afunction is added). A changed value does not always require a recompile.
Memory management#
- char*PyDataMem_NEW(size_tnbytes)#
- voidPyDataMem_FREE(char*ptr)#
- char*PyDataMem_RENEW(void*ptr,size_tnewbytes)#
Functions to allocate, free, and reallocate memory. These are usedinternally to manage array data memory unless overridden.
- voidPyDimMem_FREE(char*ptr)#
- npy_intp*PyDimMem_RENEW(void*ptr,size_tnewnd)#
Macros to allocate, free, and reallocate dimension and strides memory.
- void*PyArray_malloc(size_tnbytes)#
- voidPyArray_free(void*ptr)#
- void*PyArray_realloc(npy_intp*ptr,size_tnbytes)#
These macros use different memory allocators, depending on theconstant
NPY_USE_PYMEM
. The system malloc is used whenNPY_USE_PYMEM
is 0, ifNPY_USE_PYMEM
is 1, thenthe Python memory allocator is used.- NPY_USE_PYMEM#
- NPY_USE_PYMEM#
- intPyArray_ResolveWritebackIfCopy(PyArrayObject*obj)#
If
obj->flags
hasNPY_ARRAY_WRITEBACKIFCOPY
, this functionclears the flags,DECREF sobj->base and makes it writeable, and setsobj->base
to NULL. It thencopiesobj->data
toobj->base->data, and returns the error state ofthe copy operation. This is the opposite ofPyArray_SetWritebackIfCopyBase
. Usually this is called onceyou are finished withobj
, just beforePy_DECREF(obj)
. It may be calledmultiple times, or withNULL
input. See alsoPyArray_DiscardWritebackIfCopy
.Returns 0 if nothing was done, -1 on error, and 1 if action was taken.
Threading support#
These macros are only meaningful ifNPY_ALLOW_THREADS
evaluates True during compilation of the extension module. Otherwise,these macros are equivalent to whitespace. Python uses a single GlobalInterpreter Lock (GIL) for each Python process so that only a singlethread may execute at a time (even on multi-cpu machines). Whencalling out to a compiled function that may take time to compute (anddoes not have side-effects for other threads like updated globalvariables), the GIL should be released so that other Python threadscan run while the time-consuming calculations are performed. This canbe accomplished using two groups of macros. Typically, if one macro ina group is used in a code block, all of them must be used in the samecode block.NPY_ALLOW_THREADS
is true (defined as1
) unless thebuild option-Ddisable-threading
is set totrue
- in which caseNPY_ALLOW_THREADS
is false (0
).
- NPY_ALLOW_THREADS#
Group 1#
This group is used to call code that may take some time but does notuse any Python C-API calls. Thus, the GIL should be released duringits calculation.
- NPY_BEGIN_ALLOW_THREADS#
Equivalent to
Py_BEGIN_ALLOW_THREADS
except it usesNPY_ALLOW_THREADS
to determine if the macro ifreplaced with white-space or not.
- NPY_END_ALLOW_THREADS#
Equivalent to
Py_END_ALLOW_THREADS
except it usesNPY_ALLOW_THREADS
to determine if the macro ifreplaced with white-space or not.
- NPY_BEGIN_THREADS_DEF#
Place in the variable declaration area. This macro sets up thevariable needed for storing the Python state.
- NPY_BEGIN_THREADS#
Place right before code that does not need the Pythoninterpreter (no Python C-API calls). This macro saves thePython state and releases the GIL.
- NPY_END_THREADS#
Place right after code that does not need the Pythoninterpreter. This macro acquires the GIL and restores thePython state from the saved variable.
- voidNPY_BEGIN_THREADS_DESCR(PyArray_Descr*dtype)#
Useful to release the GIL only ifdtype does not containarbitrary Python objects which may need the Python interpreterduring execution of the loop.
- voidNPY_END_THREADS_DESCR(PyArray_Descr*dtype)#
Useful to regain the GIL in situations where it was releasedusing the BEGIN form of this macro.
- voidNPY_BEGIN_THREADS_THRESHOLDED(intloop_size)#
Useful to release the GIL only ifloop_size exceeds aminimum threshold, currently set to 500. Should be matchedwith a
NPY_END_THREADS
to regain the GIL.
Group 2#
This group is used to re-acquire the Python GIL after it has beenreleased. For example, suppose the GIL has been released (using theprevious calls), and then some path in the code (perhaps in adifferent subroutine) requires use of the Python C-API, then thesemacros are useful to acquire the GIL. These macros accomplishessentially a reverse of the previous three (acquire the LOCK savingwhat state it had) and then re-release it with the saved state.
- NPY_ALLOW_C_API_DEF#
Place in the variable declaration area to set up the necessaryvariable.
- NPY_ALLOW_C_API#
Place before code that needs to call the Python C-API (when it isknown that the GIL has already been released).
- NPY_DISABLE_C_API#
Place after code that needs to call the Python C-API (to re-releasethe GIL).
Tip
Never use semicolons after the threading support macros.
Priority#
- NPY_PRIORITY#
Default priority for arrays.
- NPY_SUBTYPE_PRIORITY#
Default subtype priority.
- NPY_SCALAR_PRIORITY#
Default scalar priority (very small)
- doublePyArray_GetPriority(PyObject*obj,doubledef)#
Return the
__array_priority__
attribute (converted to adouble) ofobj ordef if no attribute of that nameexists. Fast returns that avoid the attribute lookup are providedfor objects of typePyArray_Type
.
Default buffers#
- NPY_BUFSIZE#
Default size of the user-settable internal buffers.
- NPY_MIN_BUFSIZE#
Smallest size of user-settable internal buffers.
- NPY_MAX_BUFSIZE#
Largest size allowed for the user-settable buffers.
Other constants#
- NPY_NUM_FLOATTYPE#
The number of floating-point types
- NPY_MAXDIMS#
The maximum number of dimensions that may be used by NumPy.This is set to 64 and was 32 before NumPy 2.
Note
We encourage you to avoid
NPY_MAXDIMS
. A future version of NumPymay wish to remove any dimension limitation (and thus the constant).The limitation was created so that NumPy can use stack allocationsinternally for scratch space.If your algorithm has a reasonable maximum number of dimension youcould check and use that locally.
- NPY_MAXARGS#
The maximum number of array arguments that can be used in somefunctions. This used to be 32 before NumPy 2 and is now 64.To continue to allow using it as a check whether a number of argumentsis compatible ufuncs, this macro is now runtime dependent.
Note
We discourage any use of
NPY_MAXARGS
that isn’t explicitly tiedto checking for known NumPy limitations.
- NPY_FALSE#
Defined as 0 for use with Bool.
- NPY_TRUE#
Defined as 1 for use with Bool.
- NPY_FAIL#
The return value of failed converter functions which are called usingthe “O&” syntax in
PyArg_ParseTuple
-like functions.
- NPY_SUCCEED#
The return value of successful converter functions which are calledusing the “O&” syntax in
PyArg_ParseTuple
-like functions.
- NPY_RAVEL_AXIS#
Some NumPy functions (mainly the C-entrypoints for Python functions)have an
axis
argument. This macro may be passed foraxis=None
.Note
This macro is NumPy version dependent at runtime. The value is nowthe minimum integer. However, on NumPy 1.x
NPY_MAXDIMS
was used(at the time set to 32).
Miscellaneous Macros#
- intPyArray_SAMESHAPE(PyArrayObject*a1,PyArrayObject*a2)#
Evaluates as True if arraysa1 anda2 have the same shape.
- PyArray_MAX(a,b)#
Returns the maximum ofa andb. If (a) or (b) areexpressions they are evaluated twice.
- PyArray_MIN(a,b)#
Returns the minimum ofa andb. If (a) or (b) areexpressions they are evaluated twice.
- voidPyArray_DiscardWritebackIfCopy(PyArrayObject*obj)#
If
obj->flags
hasNPY_ARRAY_WRITEBACKIFCOPY
, this functionclears the flags,DECREF sobj->base and makes it writeable, and setsobj->base
to NULL. Incontrast toPyArray_ResolveWritebackIfCopy
it makes no attemptto copy the data fromobj->base. This undoesPyArray_SetWritebackIfCopyBase
. Usually this is called after anerror when you are finished withobj
, just beforePy_DECREF(obj)
.It may be called multiple times, or withNULL
input.
Enumerated Types#
- enumNPY_SORTKIND#
A special variable-type which can take on different values to indicatethe sorting algorithm being used.
- enumeratorNPY_QUICKSORT#
- enumeratorNPY_HEAPSORT#
- enumeratorNPY_MERGESORT#
- enumeratorNPY_STABLESORT#
Used as an alias of
NPY_MERGESORT
and vice versa.
- enumeratorNPY_NSORTS#
Defined to be the number of sorts. It is fixed at three by the need forbackwards compatibility, and consequently
NPY_MERGESORT
andNPY_STABLESORT
are aliased to each other and may refer to oneof several stable sorting algorithms depending on the data type.
- enumeratorNPY_QUICKSORT#
- enumNPY_SCALARKIND#
A special variable type indicating the number of “kinds” ofscalars distinguished in determining scalar-coercion rules. Thisvariable can take on the values:
- enumeratorNPY_NOSCALAR#
- enumeratorNPY_BOOL_SCALAR#
- enumeratorNPY_INTPOS_SCALAR#
- enumeratorNPY_INTNEG_SCALAR#
- enumeratorNPY_FLOAT_SCALAR#
- enumeratorNPY_COMPLEX_SCALAR#
- enumeratorNPY_OBJECT_SCALAR#
- enumeratorNPY_NSCALARKINDS#
Defined to be the number of scalar kinds(not including
NPY_NOSCALAR
).
- enumeratorNPY_NOSCALAR#
- enumNPY_ORDER#
An enumeration type indicating the element order that an array should beinterpreted in. When a brand new array is created, generallyonlyNPY_CORDER andNPY_FORTRANORDER are used, whereaswhen one or more inputs are provided, the order can be based on them.
- enumeratorNPY_ANYORDER#
Fortran order if all the inputs are Fortran, C otherwise.
- enumeratorNPY_CORDER#
C order.
- enumeratorNPY_FORTRANORDER#
Fortran order.
- enumeratorNPY_KEEPORDER#
An order as close to the order of the inputs as possible, evenif the input is in neither C nor Fortran order.
- enumeratorNPY_ANYORDER#
- enumNPY_CLIPMODE#
A variable type indicating the kind of clipping that should beapplied in certain functions.
- enumeratorNPY_RAISE#
The default for most operations, raises an exception if an indexis out of bounds.
- enumeratorNPY_CLIP#
Clips an index to the valid range if it is out of bounds.
- enumeratorNPY_WRAP#
Wraps an index to the valid range if it is out of bounds.
- enumeratorNPY_RAISE#
- enumNPY_SEARCHSIDE#
A variable type indicating whether the index returned should be that ofthe first suitable location (if
NPY_SEARCHLEFT
) or of the last(ifNPY_SEARCHRIGHT
).- enumeratorNPY_SEARCHLEFT#
- enumeratorNPY_SEARCHRIGHT#
- enumeratorNPY_SEARCHLEFT#
- enumNPY_SELECTKIND#
A variable type indicating the selection algorithm being used.
- enumeratorNPY_INTROSELECT#
- enumeratorNPY_INTROSELECT#
- enumNPY_CASTING#
An enumeration type indicating how permissive data conversions shouldbe. This is used by the iterator added in NumPy 1.6, and is intendedto be used more broadly in a future version.
- enumeratorNPY_NO_CASTING#
Only allow identical types.
- enumeratorNPY_EQUIV_CASTING#
Allow identical and casts involving byte swapping.
- enumeratorNPY_SAFE_CASTING#
Only allow casts which will not cause values to be rounded,truncated, or otherwise changed.
- enumeratorNPY_SAME_KIND_CASTING#
Allow any safe casts, and casts between types of the same kind.For example, float64 -> float32 is permitted with this rule.
- enumeratorNPY_UNSAFE_CASTING#
Allow any cast, no matter what kind of data loss may occur.
- enumeratorNPY_NO_CASTING#