Data types — NumPy v1.18.dev0 Manual (2024)

Array types and conversions between types

NumPy supports a much greater variety of numerical types than Python does.This section shows which are available, and how to modify an array’s data-type.

The primitive types supported are tied closely to those in C:

Numpy type

C type

Description

np.bool_

bool

Boolean (True or False) stored as a byte

np.byte

signed char

Platform-defined

np.ubyte

unsigned char

Platform-defined

np.short

short

Platform-defined

np.ushort

unsigned short

Platform-defined

np.intc

int

Platform-defined

np.uintc

unsigned int

Platform-defined

np.int_

long

Platform-defined

np.uint

unsigned long

Platform-defined

np.longlong

long long

Platform-defined

np.ulonglong

unsigned long long

Platform-defined

np.half / np.float16

Half precision float:sign bit, 5 bits exponent, 10 bits mantissa

np.single

float

Platform-defined single precision float:typically sign bit, 8 bits exponent, 23 bits mantissa

np.double

double

Platform-defined double precision float:typically sign bit, 11 bits exponent, 52 bits mantissa.

np.longdouble

long double

Platform-defined extended-precision float

np.csingle

float complex

Complex number, represented by two single-precision floats (real and imaginary components)

np.cdouble

double complex

Complex number, represented by two double-precision floats (real and imaginary components).

np.clongdouble

long double complex

Complex number, represented by two extended-precision floats (real and imaginary components).

Since many of these have platform-dependent definitions, a set of fixed-sizealiases are provided:

Numpy type

C type

Description

np.int8

int8_t

Byte (-128 to 127)

np.int16

int16_t

Integer (-32768 to 32767)

np.int32

int32_t

Integer (-2147483648 to 2147483647)

np.int64

int64_t

Integer (-9223372036854775808 to 9223372036854775807)

np.uint8

uint8_t

Unsigned integer (0 to 255)

np.uint16

uint16_t

Unsigned integer (0 to 65535)

np.uint32

uint32_t

Unsigned integer (0 to 4294967295)

np.uint64

uint64_t

Unsigned integer (0 to 18446744073709551615)

np.intp

intptr_t

Integer used for indexing, typically the same as ssize_t

np.uintp

uintptr_t

Integer large enough to hold a pointer

np.float32

float

np.float64 / np.float_

double

Note that this matches the precision of the builtin python float.

np.complex64

float complex

Complex number, represented by two 32-bit floats (real and imaginary components)

np.complex128 / np.complex_

double complex

Note that this matches the precision of the builtin python complex.

NumPy numerical types are instances of dtype (data-type) objects, eachhaving unique characteristics. Once you have imported NumPy using

>>> import numpy as np

the dtypes are available as np.bool_, np.float32, etc.

Advanced types, not listed in the table above, are explored insection Structured arrays.

There are 5 basic numerical types representing booleans (bool), integers (int),unsigned integers (uint) floating point (float) and complex. Those with numbersin their name indicate the bitsize of the type (i.e. how many bits are neededto represent a single value in memory). Some types, such as int andintp, have differing bitsizes, dependent on the platforms (e.g. 32-bitvs. 64-bit machines). This should be taken into account when interfacingwith low-level code (such as C or Fortran) where the raw memory is addressed.

Data-types can be used as functions to convert python numbers to array scalars(see the array scalar section for an explanation), python sequences of numbersto arrays of that type, or as arguments to the dtype keyword that many numpyfunctions or methods accept. Some examples:

>>> import numpy as np>>> x = np.float32(1.0)>>> x1.0>>> y = np.int_([1,2,4])>>> yarray([1, 2, 4])>>> z = np.arange(3, dtype=np.uint8)>>> zarray([0, 1, 2], dtype=uint8)

Array types can also be referred to by character codes, mostly to retainbackward compatibility with older packages such as Numeric. Somedocumentation may still refer to these, for example:

>>> np.array([1, 2, 3], dtype='f')array([ 1., 2., 3.], dtype=float32)

We recommend using dtype objects instead.

To convert the type of an array, use the .astype() method (preferred) orthe type itself as a function. For example:

>>> z.astype(float) array([ 0., 1., 2.])>>> np.int8(z)array([0, 1, 2], dtype=int8)

Note that, above, we use the Python float object as a dtype. NumPy knowsthat int refers to np.int_, bool means np.bool_,that float is np.float_ and complex is np.complex_.The other data-types do not have Python equivalents.

To determine the type of an array, look at the dtype attribute:

>>> z.dtypedtype('uint8')

dtype objects also contain information about the type, such as its bit-widthand its byte-order. The data type can also be used indirectly to queryproperties of the type, such as whether it is an integer:

>>> d = np.dtype(int)>>> ddtype('int32')>>> np.issubdtype(d, np.integer)True>>> np.issubdtype(d, np.floating)False

Array Scalars

NumPy generally returns elements of arrays as array scalars (a scalarwith an associated dtype). Array scalars differ from Python scalars, butfor the most part they can be used interchangeably (the primaryexception is for versions of Python older than v2.x, where integer arrayscalars cannot act as indices for lists and tuples). There are someexceptions, such as when code requires very specific attributes of a scalaror when it checks specifically whether a value is a Python scalar. Generally,problems are easily fixed by explicitly converting array scalarsto Python scalars, using the corresponding Python type function(e.g., int, float, complex, str, unicode).

The primary advantage of using array scalars is thatthey preserve the array type (Python may not have a matching scalar typeavailable, e.g. int16). Therefore, the use of array scalars ensuresidentical behaviour between arrays and scalars, irrespective of whether thevalue is inside an array or not. NumPy scalars also have many of the samemethods arrays do.

Overflow Errors

The fixed size of NumPy numeric types may cause overflow errors when a valuerequires more memory than available in the data type. For example, numpy.power evaluates 100 * 10 ** 8 correctly for 64-bit integers,but gives 1874919424 (incorrect) for a 32-bit integer.

>>> np.power(100, 8, dtype=np.int64)10000000000000000>>> np.power(100, 8, dtype=np.int32)1874919424

The behaviour of NumPy and Python integer types differs significantly forinteger overflows and may confuse users expecting NumPy integers to behavesimilar to Python’s int. Unlike NumPy, the size of Python’s int isflexible. This means Python integers may expand to accommodate any integer andwill not overflow.

NumPy provides numpy.iinfo and numpy.finfo to verify theminimum or maximum values of NumPy integer and floating point valuesrespectively

>>> np.iinfo(int) # Bounds of the default integer on this system.iinfo(min=-9223372036854775808, max=9223372036854775807, dtype=int64)>>> np.iinfo(np.int32) # Bounds of a 32-bit integeriinfo(min=-2147483648, max=2147483647, dtype=int32)>>> np.iinfo(np.int64) # Bounds of a 64-bit integeriinfo(min=-9223372036854775808, max=9223372036854775807, dtype=int64)

If 64-bit integers are still too small the result may be cast to afloating point number. Floating point numbers offer a larger, but inexact,range of possible values.

>>> np.power(100, 100, dtype=np.int64) # Incorrect even with 64-bit int0>>> np.power(100, 100, dtype=np.float64)1e+200

Extended Precision

Python’s floating-point numbers are usually 64-bit floating-point numbers,nearly equivalent to np.float64. In some unusual situations it may beuseful to use floating-point numbers with more precision. Whether thisis possible in numpy depends on the hardware and on the developmentenvironment: specifically, x86 machines provide hardware floating-pointwith 80-bit precision, and while most C compilers provide this as theirlong double type, MSVC (standard for Windows builds) makeslong double identical to double (64 bits). NumPy makes thecompiler’s long double available as np.longdouble (andnp.clongdouble for the complex numbers). You can find out what yournumpy provides with np.finfo(np.longdouble).

NumPy does not provide a dtype with more precision than C’slong double; in particular, the 128-bit IEEE quad precisiondata type (FORTRAN’s REAL*16) is not available.

For efficient memory alignment, np.longdouble is usually storedpadded with zero bits, either to 96 or 128 bits. Which is more efficientdepends on hardware and development environment; typically on 32-bitsystems they are padded to 96 bits, while on 64-bit systems they aretypically padded to 128 bits. np.longdouble is padded to the systemdefault; np.float96 and np.float128 are provided for users whowant specific padding. In spite of the names, np.float96 andnp.float128 provide only as much precision as np.longdouble,that is, 80 bits on most x86 machines and 64 bits in standardWindows builds.

Be warned that even if np.longdouble offers more precision thanpython float, it is easy to lose that extra precision, sincepython often forces values to pass through float. For example,the % formatting operator requires its arguments to be convertedto standard python types, and it is therefore impossible to preserveextended precision even if many decimal places are requested. It canbe useful to test your code with the value1 + np.finfo(np.longdouble).eps.

Data types — NumPy v1.18.dev0 Manual (2024)

FAQs

What are the NumPy data types? ›

NumPy Data Types
  • strings - used to represent text data, the text is given under quote marks. e.g. "ABCD"
  • integer - used to represent integer numbers. e.g. -1, -2, -3.
  • float - used to represent real numbers. e.g. 1.2, 42.42.
  • boolean - used to represent True or False.
  • complex - used to represent complex numbers.

How to check the data type of a NumPy array? ›

You can check the type of data present in the NumPy array using the '. dtype' attribute. The data type of array 'arr' is 'int' (integer). Here, '32' is related to memory allocation.

How to set data type in NumPy array? ›

The numpy. astype() method is used to change the data type NumPy array from one data type to another. The function takes an argument which is the target data type. The function supports all the generic types and built-in types of data.

How to create NumPy array with different data types? ›

NumPy to create three arrays with different data types: array1 with int32, array2 with float64, and array3 with object type using dtype. Then, the np. hstack function horizontally stacks these arrays, creating combined_array .

What are the 4 different data types in Python? ›

They determine the type of values variables can hold and specify the operations that can be performed on those values. For instance, Python has several built-in data types, including numeric types (int, float, complex), string (str), boolean (bool), and collection types (list, tuple, dict, set).

How to check data type in Python? ›

To determine the type of a variable in Python, use the built-in type() function. In Python, everything is an object. As a result, when you use the type() function to print the type of a variable's value to the console, it returns the class type of the object.

How to convert NumPy array data type? ›

To convert the type of an array, use the .astype() method. For example: >>> z.astype(np.float64) array([0., 1., 2.]) Note that, above, we could have used the Python float object as a dtype instead of numpy.float64 .

What is the default data type of NumPy arrays? ›

The default data type: float64 . The 24 built-in array scalar type objects all convert to an associated data-type object. This is true for their sub-classes as well.

How many types of arrays are there in NumPy? ›

The list of various types of data types provided by NumPy are given below:
Data TypeDescription
float32Single-precision float values
float64Double-precision float values
complex_Complex values
complex64Represent two 32-bit float complex values (real and imaginary)
15 more rows
Sep 4, 2023

How to convert list data type to NumPy array? ›

array() Function. The simplest way to convert a Python list to a NumPy array is by using the `numpy. array()` function. This function takes a Python list as input and returns a NumPy array.

Which attribute is used to find the data type of a NumPy array? ›

dtype tells the data type of the elements of a NumPy array. In NumPy array, all the elements have the same data type. itemsize returns the size (in bytes) of each element of a NumPy array.

How to change NumPy array data type to int? ›

Numpy astype() Method:

The astype(int) function converts the floating-point numbers in the array to integers. Note that this function truncates the decimal part of the number, rather than rounding to the nearest integer.

How many data types are in NumPy? ›

Types of data in NumPy
Data typeDescription
int8Integers ranging from -128 to 127
int16Integers ranging from -32 768 to 32 767
int32Integers ranging from -2 147 483 648 to 2 147 483 647
int64Integers ranging from -9 223 372 036 854 775 808 to 9 223 372 036 854 775 807
6 more rows

How to check the type of NumPy array? ›

To check if an np array, c , has elements of type float, c. dtype == np. floating works for me. All entries in a numpy array are of the same type.

Can we store different data types in an array? ›

An array can be of any data type, but can only hold a single data type. Specifically, you can declare an array that holds strings and an array that holds integers, but you cannot declare a single array that holds both strings AND integers.

What are the available types in NumPy? ›

Array types and conversions between types
Numpy typeC typeDescription
numpy.bool_boolBoolean (True or False) stored as a byte
numpy.bytesigned charPlatform-defined
numpy.ubyteunsigned charPlatform-defined
numpy.shortshortPlatform-defined
14 more rows

What is dtype in NumPy? ›

dtype (data-type) objects, each having unique characteristics. Once you have imported NumPy using import numpy as np you can create arrays with a specified dtype using the scalar types in the numpy top-level API, e.g. numpy. bool , numpy. float32 , etc.

What are the data structures of NumPy? ›

Types of data structures
  • Linked lists. A linked list is a sequence of elements where each one contains reference information for the element next to it. ...
  • Arrays. An array is a group of data elements arranged in adjacent memory locations. ...
  • Stacks. ...
  • Queue. ...
  • Graphs. ...
  • Trees. ...
  • Binary trees. ...
  • Tries.
Apr 22, 2024

What is the basic data structure in NumPy? ›

NumPy is a Python library that can be used for scientific and numerical applications and is the tool to use for linear algebra operations. The main data structure in NumPy is the ndarray, which is a shorthand name for N-dimensional array. When working with NumPy, data in an ndarray is simply referred to as an array.

References

Top Articles
Hultafors MRS Metric Rafter Square - 18cm | bol
Roof Framing: How to Measure, Cut, and Build Roof Rafters | Fixr
Tripadvisor Antigua Forum
Gaseous Form Pathfinder
Canvas Rjuhsd
Camping World Of New River
Pga Scores Cbs
Walmart Automotive Number
Academic Calendar Biola
St Vrain Chain Gang
Adopted. Abused. Abandoned. How a Michigan boy's parents left him in Jamaica
Ohio Lottery Full Site
R Umineko
Unlockme Cintas
Behind The Scenes Of White Christmas (1954) - Casting, Choreography, Costumes, And Music | TrainTracksHQ
The Dillards: From Mayberry's Darlings to Progressive Bluegrass Pioneers
The Obscure Spring Watch Online Free
Demystifying the C-Suite: A Close Look at the Top Executive Roles - 33rd Square
Magicseaweed Capitola
Www Craigslist Antelope Valley
Army Dlc 1 Cheat
Craigslist Truck
Cavender’s 50th Anniversary: How the Cavender Family Built — and Continues to Grow — a Western Wear Empire Using Common Sense values
Bx11
Vioc Credit Card Charge
Kim Dotcom to fight extradition, says he won't get fair trial in US
Www.publicsurplus.com Motor Pool
Atlanticbb Message Center
The Autopsy of Jane Doe - Kritik | Film 2016 | Moviebreak.de
Directions To American Legion
Pokio.io
Express-Reisepass beantragen - hamburg.de
Horseheads Schooltool
Ottumwa Evening Post Obits
Kayak Parts Amazon
Coors Field Seats In The Shade
Match The Criminal To The Weapon
Diminutiv: Definition, Bedeutung und Beispiele
352-730-1982
How Much Does Hasa Pay For Rent 2022
San Diego Box Score
Phoenix | Arizona, Population, Map, & Points of Interest
Lacy Aaron Schmidt Where Is He Now
Walgreens Wellington Green
Smartmove Internet Provider
Exploring The Craigslist Washington DC Marketplace - A Complete Overview
Top 10 websites to play unblocked games
Ebony Grinding Lesbian
Luminous Mysteries - Rosary Meditations
CareLink™ Personal Software | Medtronic
Lesbian Wicked Whims Animations
O'reilly's Covington Tennessee
Latest Posts
Article information

Author: Virgilio Hermann JD

Last Updated:

Views: 6038

Rating: 4 / 5 (61 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Virgilio Hermann JD

Birthday: 1997-12-21

Address: 6946 Schoen Cove, Sipesshire, MO 55944

Phone: +3763365785260

Job: Accounting Engineer

Hobby: Web surfing, Rafting, Dowsing, Stand-up comedy, Ghost hunting, Swimming, Amateur radio

Introduction: My name is Virgilio Hermann JD, I am a fine, gifted, beautiful, encouraging, kind, talented, zealous person who loves writing and wants to share my knowledge and understanding with you.