NumPy data types

Introduction to NumPy

Izzy Weber

Core Curriculum Manager, DataCamp

NumPy vs. Python data types

 

Sample Python data types:

  • int
  • float

 

Sample NumPy data types:

  • np.int64
  • np.int32
  • np.float64
  • np.float32
Introduction to NumPy

Bits and bytes

The number 10436 represented in binary is:

An image of the number 10436 in binary  

np.int32 can store 4,294,967,296 integers:

A diagram of np.int32 storage capacity

Introduction to NumPy

Bits and bytes

The number 10436 represented in binary is:

An image of the number 10436 in binary  

np.int32 can store 4,294,967,296 integers:

A diagram of np.int32 storage capacity

Introduction to NumPy

The .dtype attribute

np.array([1.32, 5.78, 175.55]).dtype
dtype('float64')
Introduction to NumPy

Default data types

int_array = np.array([[1, 2, 3], [4, 5, 6]])
int_array.dtype
dtype('int64')
Introduction to NumPy

String data

np.array(["Introduction", "to", "NumPy"]).dtype
dtype('<U12')
Introduction to NumPy

dtype as an argument

float32_array = np.array([1.32, 5.78, 175.55], dtype=np.float32)
float32_array.dtype
dtype('float32')
Introduction to NumPy

Type conversion

boolean_array = np.array([[True, False], [False, False]], dtype=np.bool_)
boolean_array.astype(np.int32)
array([[1, 0],
       [0, 0]], dtype=int32)
Introduction to NumPy

Type coercion

np.array([True, "Boop", 42, 42.42])
array(['True', 'Boop', '42', '42.42'], dtype='<U5')
Introduction to NumPy

Type coercion hierarchy

Adding a float to an array of integers will change all integers into floats:

np.array([0, 42, 42.42]).dtype
dtype('float64')

 

Adding an integer to an array of booleans will change all booleans in to integers:

np.array([True, False, 42]).dtype
dtype('int64')
Introduction to NumPy

Let's practice!

Introduction to NumPy

Preparing Video For Download...