Scalars#

Python defines only one type of a particular data class (there is onlyone integer type, one floating-point type, etc.). This can beconvenient in applications that don’t need to be concerned with allthe ways data can be represented in a computer. For scientificcomputing, however, more control is often needed.

In NumPy, there are 24 new fundamental Python types to describedifferent types of scalars. These type descriptors are mostly based onthe types available in the C language that CPython is written in, withseveral additional types compatible with Python’s types.

Array scalars have the same attributes and methods asndarrays.[1] This allows one to treat items of an array partly onthe same footing as arrays, smoothing out rough edges that result whenmixing scalar and array operations.

Array scalars live in a hierarchy (see the Figure below) of datatypes. They can be detected using the hierarchy: For example,isinstance(val,np.generic) will returnTrue ifval isan array scalar object. Alternatively, what kind of array scalar ispresent can be determined using other members of the data typehierarchy. Thus, for exampleisinstance(val,np.complexfloating)will returnTrue ifval is a complex valued type, whileisinstance(val,np.flexible) will return true ifval is oneof the flexible itemsize array types (str_,bytes_,void).

../_images/dtype-hierarchy.png

Figure: Hierarchy of type objects representing the array datatypes. Not shown are the two integer typesintp anduintp which are used for indexing (the same as thedefault integer since NumPy 2).#

[1]

However, array scalars are immutable, so none of the arrayscalar attributes are settable.

Built-in scalar types#

The built-in scalar types are shown below. The C-like names are associated with character codes,which are shown in their descriptions. Use of the character codes, however,is discouraged.

Some of the scalar types are essentially equivalent to fundamentalPython types and therefore inherit from them as well as from thegeneric array scalar type:

Thebool_ data type is very similar to the Pythonbool but does not inherit from it because Python’sbool does not allow itself to be inherited from, andon the C-level the size of the actual bool data is not the same as aPython Boolean scalar.

Warning

Theint_ type doesnot inherit from the built-inint, because typeint is not a fixed-widthinteger type.

Tip

The default data type in NumPy isdouble.

classnumpy.generic[source]#

Base class for numpy scalar types.

Class from which most (all?) numpy scalar types are derived. Forconsistency, exposes the same API asndarray, despite manyconsequent attributes being either “get-only,” or completely irrelevant.This is the class from which it is strongly suggested users should derivecustom scalar types.

classnumpy.number[source]#

Abstract base class of all numeric scalar types.

Integer types#

classnumpy.integer[source]#

Abstract base class of all integer scalar types.

Note

The numpy integer types mirror the behavior of C integers, and can thereforebe subject toOverflow errors.

Signed integer types#

classnumpy.signedinteger[source]#

Abstract base class of all signed integer scalar types.

classnumpy.byte[source]#

Signed integer type, compatible with Cchar.

Character code:

'b'

Canonical name:

numpy.byte

Alias on this platform (Linux x86_64):

numpy.int8: 8-bit signed integer (-128 to127).

classnumpy.short[source]#

Signed integer type, compatible with Cshort.

Character code:

'h'

Canonical name:

numpy.short

Alias on this platform (Linux x86_64):

numpy.int16: 16-bit signed integer (-32_768 to32_767).

classnumpy.intc[source]#

Signed integer type, compatible with Cint.

Character code:

'i'

Canonical name:

numpy.intc

Alias on this platform (Linux x86_64):

numpy.int32: 32-bit signed integer (-2_147_483_648 to2_147_483_647).

classnumpy.int_[source]#

Default signed integer type, 64bit on 64bit systems and 32bit on 32bitsystems.

Character code:

'l'

Canonical name:

numpy.int_

Alias on this platform (Linux x86_64):

numpy.int64: 64-bit signed integer (-9_223_372_036_854_775_808 to9_223_372_036_854_775_807).

Alias on this platform (Linux x86_64):

numpy.intp: Signed integer large enough to fit pointer, compatible with Cintptr_t.

numpy.long[source]#

alias ofint_

classnumpy.longlong[source]#

Signed integer type, compatible with Clonglong.

Character code:

'q'

Unsigned integer types#

classnumpy.unsignedinteger[source]#

Abstract base class of all unsigned integer scalar types.

classnumpy.ubyte[source]#

Unsigned integer type, compatible with Cunsignedchar.

Character code:

'B'

Canonical name:

numpy.ubyte

Alias on this platform (Linux x86_64):

numpy.uint8: 8-bit unsigned integer (0 to255).

classnumpy.ushort[source]#

Unsigned integer type, compatible with Cunsignedshort.

Character code:

'H'

Canonical name:

numpy.ushort

Alias on this platform (Linux x86_64):

numpy.uint16: 16-bit unsigned integer (0 to65_535).

classnumpy.uintc[source]#

Unsigned integer type, compatible with Cunsignedint.

Character code:

'I'

Canonical name:

numpy.uintc

Alias on this platform (Linux x86_64):

numpy.uint32: 32-bit unsigned integer (0 to4_294_967_295).

classnumpy.uint[source]#

Unsigned signed integer type, 64bit on 64bit systems and 32bit on 32bitsystems.

Character code:

'L'

Canonical name:

numpy.uint

Alias on this platform (Linux x86_64):

numpy.uint64: 64-bit unsigned integer (0 to18_446_744_073_709_551_615).

Alias on this platform (Linux x86_64):

numpy.uintp: Unsigned integer large enough to fit pointer, compatible with Cuintptr_t.

numpy.ulong[source]#

alias ofuint

classnumpy.ulonglong[source]#

Signed integer type, compatible with Cunsignedlonglong.

Character code:

'Q'

Inexact types#

classnumpy.inexact[source]#

Abstract base class of all numeric scalar types with a (potentially)inexact representation of the values in its range, such asfloating-point numbers.

Note

Inexact scalars are printed using the fewest decimal digits needed todistinguish their value from other values of the same datatype,by judicious rounding. See theunique parameter offormat_float_positional andformat_float_scientific.

This means that variables with equal binary values but whose datatypes are ofdifferent precisions may display differently:

>>>importnumpyasnp
>>>f16=np.float16("0.1")>>>f32=np.float32(f16)>>>f64=np.float64(f32)>>>f16==f32==f64True>>>f16,f32,f64(0.1, 0.099975586, 0.0999755859375)

Note that none of these floats hold the exact value\(\frac{1}{10}\);f16 prints as0.1 because it is as close to that value as possible,whereas the other types do not as they have more precision and therefore havecloser values.

Conversely, floating-point scalars of different precisions which approximatethe same decimal value may compare unequal despite printing identically:

>>>f16=np.float16("0.1")>>>f32=np.float32("0.1")>>>f64=np.float64("0.1")>>>f16==f32==f64False>>>f16,f32,f64(0.1, 0.1, 0.1)

Floating-point types#

classnumpy.floating[source]#

Abstract base class of all floating-point scalar types.

classnumpy.half[source]#

Half-precision floating-point number type.

Character code:

'e'

Canonical name:

numpy.half

Alias on this platform (Linux x86_64):

numpy.float16: 16-bit-precision floating-point number type: sign bit, 5 bits exponent, 10 bits mantissa.

classnumpy.single[source]#

Single-precision floating-point number type, compatible with Cfloat.

Character code:

'f'

Canonical name:

numpy.single

Alias on this platform (Linux x86_64):

numpy.float32: 32-bit-precision floating-point number type: sign bit, 8 bits exponent, 23 bits mantissa.

classnumpy.double(x=0,/)[source]#

Double-precision floating-point number type, compatible with Pythonfloat and Cdouble.

Character code:

'd'

Canonical name:

numpy.double

Alias on this platform (Linux x86_64):

numpy.float64: 64-bit precision floating-point number type: sign bit, 11 bits exponent, 52 bits mantissa.

classnumpy.longdouble[source]#

Extended-precision floating-point number type, compatible with Clongdouble but not necessarily with IEEE 754 quadruple-precision.

Character code:

'g'

Alias on this platform (Linux x86_64):

numpy.float128: 128-bit extended-precision floating-point number type.

Complex floating-point types#

classnumpy.complexfloating[source]#

Abstract base class of all complex number scalar types that are made up offloating-point numbers.

classnumpy.csingle[source]#

Complex number type composed of two single-precision floating-pointnumbers.

Character code:

'F'

Canonical name:

numpy.csingle

Alias on this platform (Linux x86_64):

numpy.complex64: Complex number type composed of 2 32-bit-precision floating-point numbers.

classnumpy.cdouble(real=0,imag=0)[source]#

Complex number type composed of two double-precision floating-pointnumbers, compatible with Pythoncomplex.

Character code:

'D'

Canonical name:

numpy.cdouble

Alias on this platform (Linux x86_64):

numpy.complex128: Complex number type composed of 2 64-bit-precision floating-point numbers.

classnumpy.clongdouble[source]#

Complex number type composed of two extended-precision floating-pointnumbers.

Character code:

'G'

Alias on this platform (Linux x86_64):

numpy.complex256: Complex number type composed of 2 128-bit extended-precision floating-point numbers.

Other types#

numpy.bool_[source]#

alias ofbool

classnumpy.bool[source]#

Boolean type (True or False), stored as a byte.

Warning

Thebool type is not a subclass of theint_ type(thebool is not even a number type). This is differentthan Python’s default implementation ofbool as asub-class ofint.

Character code:

'?'

classnumpy.datetime64[source]#

If created from a 64-bit integer, it represents an offset from1970-01-01T00:00:00.If created from string, the string can be in ISO 8601 dateor datetime format.

When parsing a string to create a datetime object, if the string containsa trailing timezone (A ‘Z’ or a timezone offset), the timezone will bedropped and a User Warning is given.

Datetime64 objects should be considered to be UTC and therefore have anoffset of +0000.

>>>np.datetime64(10,'Y')np.datetime64('1980')>>>np.datetime64('1980','Y')np.datetime64('1980')>>>np.datetime64(10,'D')np.datetime64('1970-01-11')

SeeDatetimes and timedeltas for more information.

Character code:

'M'

classnumpy.timedelta64[source]#

A timedelta stored as a 64-bit integer.

SeeDatetimes and timedeltas for more information.

Character code:

'm'

classnumpy.object_[source]#

Any Python object.

Character code:

'O'

Note

The data actually stored in object arrays(i.e., arrays having dtypeobject_) are references toPython objects, not the objects themselves. Hence, object arraysbehave more like usual Pythonlists, in the sensethat their contents need not be of the same Python type.

The object type is also special because an array containingobject_ items does not return anobject_ objecton item access, but instead returns the actual object thatthe array item refers to.

The following data types areflexible: they have no predefinedsize and the data they describe can be of different length in differentarrays. (In the character codes# is an integer denoting how manyelements the data type consists of.)

classnumpy.flexible[source]#

Abstract base class of all scalar types without predefined length.The actual size of these types depends on the specificnumpy.dtypeinstantiation.

classnumpy.character[source]#

Abstract base class of all character string scalar types.

classnumpy.bytes_[source]#

A byte string.

When used in arrays, this type strips trailing null bytes.

Character code:

'S'

classnumpy.str_[source]#

A unicode string.

This type strips trailing null codepoints.

>>>s=np.str_("abc\x00")>>>s'abc'

Unlike the builtinstr, this supports theBuffer Protocol, exposing its contents as UCS4:

>>>m=memoryview(np.str_("abc"))>>>m.format'3w'>>>m.tobytes()b'a\x00\x00\x00b\x00\x00\x00c\x00\x00\x00'
Character code:

'U'

classnumpy.void(length_or_data,/,dtype=None)[source]#

Create a new structured or unstructured void scalar.

Parameters:
length_or_dataint, array-like, bytes-like, object

One of multiple meanings (see notes). The length orbytes data of an unstructured void. Or alternatively,the data to be stored in the new scalar whendtypeis provided.This can be an array-like, in which case an array maybe returned.

dtypedtype, optional

If provided the dtype of the new scalar. This dtype mustbe “void” dtype (i.e. a structured or unstructured void,see alsoStructured datatypes).

New in version 1.24.

Notes

For historical reasons and because void scalars can represent botharbitrary byte data and structured dtypes, the void constructorhas three calling conventions:

  1. np.void(5) creates adtype="V5" scalar filled with five\0 bytes. The 5 can be a Python or NumPy integer.

  2. np.void(b"bytes-like") creates a void scalar from the byte string.The dtype itemsize will match the byte string length, here"V10".

  3. When adtype= is passed the call is roughly the same as anarray creation. However, a void scalar rather than array is returned.

Please see the examples which show all three different conventions.

Examples

>>>np.void(5)np.void(b'\x00\x00\x00\x00\x00')>>>np.void(b'abcd')np.void(b'\x61\x62\x63\x64')>>>np.void((3.2,b'eggs'),dtype="d,S5")np.void((3.2, b'eggs'), dtype=[('f0', '<f8'), ('f1', 'S5')])>>>np.void(3,dtype=[('x',np.int8),('y',np.int8)])np.void((3, 3), dtype=[('x', 'i1'), ('y', 'i1')])
Character code:

'V'

Warning

SeeNote on string types.

Numeric Compatibility: If you used old typecode characters in yourNumeric code (which was never recommended), you will need to changesome of them to the new characters. In particular, the neededchanges arec->S1,b->B,1->b,s->h,w->H, andu->I. These changes make the type characterconvention more consistent with other Python modules such as thestruct module.

Sized aliases#

Along with their (mostly)C-derived names, the integer, float, and complex data-types are alsoavailable using a bit-width convention so that an array of the rightsize can always be ensured. Two aliases (numpy.intp andnumpy.uintp)pointing to the integer type that is sufficiently large to hold a C pointerare also provided.

numpy.int8[source]#
numpy.int16#
numpy.int32#
numpy.int64#

Aliases for the signed integer types (one ofnumpy.byte,numpy.short,numpy.intc,numpy.int_,numpy.long andnumpy.longlong)with the specified number of bits.

Compatible with the C99int8_t,int16_t,int32_t, andint64_t, respectively.

numpy.uint8[source]#
numpy.uint16#
numpy.uint32#
numpy.uint64#

Alias for the unsigned integer types (one ofnumpy.ubyte,numpy.ushort,numpy.uintc,numpy.uint,numpy.ulong andnumpy.ulonglong)with the specified number of bits.

Compatible with the C99uint8_t,uint16_t,uint32_t, anduint64_t, respectively.

numpy.intp[source]#

Alias for the signed integer type (one ofnumpy.byte,numpy.short,numpy.intc,numpy.int_,numpy.long andnumpy.longlong)that is used as a default integer and for indexing.

Compatible with the CPy_ssize_t.

Character code:

'n'

Changed in version 2.0:Before NumPy 2, this had the same size as a pointer. In practice thisis almost always identical, but the character code'p' maps to the Cintptr_t. The character code'n' was added in NumPy 2.0.

numpy.uintp[source]#

Alias for the unsigned integer type that is the same size asintp.

Compatible with the Csize_t.

Character code:

'N'

Changed in version 2.0:Before NumPy 2, this had the same size as a pointer. In practice thisis almost always identical, but the character code'P' maps to the Cuintptr_t. The character code'N' was added in NumPy 2.0.

numpy.float16[source]#

alias ofhalf

numpy.float32[source]#

alias ofsingle

numpy.float64[source]#

alias ofdouble

numpy.float96#
numpy.float128[source]#

Alias fornumpy.longdouble, named after its size in bits.The existence of these aliases depends on the platform.

numpy.complex64[source]#

alias ofcsingle

numpy.complex128[source]#

alias ofcdouble

numpy.complex192#
numpy.complex256[source]#

Alias fornumpy.clongdouble, named after its size in bits.The existence of these aliases depends on the platform.

Attributes#

The array scalar objects have anarraypriority ofNPY_SCALAR_PRIORITY(-1,000,000.0). They also do not (yet) have actypesattribute. Otherwise, they share the same attributes as arrays:

generic.flags

The integer value of flags.

generic.shape

Tuple of array dimensions.

generic.strides

Tuple of bytes steps in each dimension.

generic.ndim

The number of array dimensions.

generic.data

Pointer to start of data.

generic.size

The number of elements in the gentype.

generic.itemsize

The length of one element in bytes.

generic.base

Scalar attribute identical to the corresponding array attribute.

generic.dtype

Get array data-descriptor.

generic.real

The real part of the scalar.

generic.imag

The imaginary part of the scalar.

generic.flat

A 1-D view of the scalar.

generic.T

Scalar attribute identical to the corresponding array attribute.

generic.__array_interface__

Array protocol: Python side

generic.__array_struct__

Array protocol: struct

generic.__array_priority__

Array priority.

generic.__array_wrap__

__array_wrap__ implementation for scalar types

Indexing#

Array scalars can be indexed like 0-dimensional arrays: ifx is anarray scalar,

  • x[()] returns a copy of array scalar

  • x[...] returns a 0-dimensionalndarray

  • x['field-name'] returns the array scalar in the fieldfield-name.(x can have fields, for example, when it corresponds to a structured data type.)

Methods#

Array scalars have exactly the same methods as arrays. The defaultbehavior of these methods is to internally convert the scalar to anequivalent 0-dimensional array and to call the corresponding arraymethod. In addition, math operations on array scalars are defined sothat the same hardware flags are set and used to interpret the resultsas forufunc, so that the error state used for ufuncsalso carries over to the math on array scalars.

The exceptions to the above rules are given below:

generic.__array__

sc.__array__(dtype) return 0-dim array from scalar with specified dtype

generic.__array_wrap__

__array_wrap__ implementation for scalar types

generic.squeeze

Scalar method identical to the corresponding array attribute.

generic.byteswap

Scalar method identical to the corresponding array attribute.

generic.__reduce__

Helper for pickle.

generic.__setstate__

generic.setflags

Scalar method identical to the corresponding array attribute.

Utility method for typing:

number.__class_getitem__(item, /)

Return a parametrized wrapper around thenumber type.

Defining new types#

There are two ways to effectively define a new array scalar type(apart from composing structured typesdtypes fromthe built-in scalar types): One way is to simply subclass thendarray and overwrite the methods of interest. This will work toa degree, but internally certain behaviors are fixed by the data type ofthe array. To fully customize the data type of an array you need todefine a new data-type, and register it with NumPy. Such new types can onlybe defined in C, using theNumPy C-API.