Tools
Text

Type Conversion

Lesson 2 Chapter 1

Now, let's turn a list to a Numpy array. For now, let's just focus on the data types and conversion, later in this course, you will learn how to define Numpy arrays in details.

# Import Numpy library
import numpy as np

# Define a Python list
a = [1, 2, 1.3]
print('Type "a": ', type(a))

# Turn Python list into a Numpy array of type np.int32 (Integer (-2147483648 to 2147483647))
b = np.int32(a)
print('Array "b": ', b)
print('Type array "b": ', type(b))
print('Array "b" data type: ', b.dtype)

# Turn Python list into a Numpy array of type np.float32 (same as Python float)
c = np.float32(a)
print('Array "c": ', c)
print('Type array "c": ', type(c))
print('Array "c" data type: ', c.dtype)

Type "a":  <class 'list'>
Array "b":  [1 2 1]
Type array "b":  <class 'numpy.ndarray'>
Array "b" data type:  int32
Array "c":  [1.  2.  1.3]
Type array "c":  <class 'numpy.ndarray'>
Array "c" data type:  float32

We used the .dtype Numpy method to realize what is the data type inside the array. The recommended way to change the type of a Numpy array is the usage of .astype() method. Take a look at the following example:

# Import Numpy library
import numpy as np

# Define a Python list
a = [1, 2, 4]
print('Type "a": ', type(a))

# Turn Python list into a Numpy array of type np.int32 (Integer (-2147483648 to 2147483647))
b = np.int32(a)
print('Array "b": ', b)
print('Type array "b": ', type(b))

# Turn Python list into a Numpy array of type np.float32 (same as Python float)
c = b.astype(np.float32)
print('Array "c": ', c)
print('Type array "c": ', type(c))

Type "a":  <class 'list'>
Array "b":  [1 2 4]
Type array "b":  <class 'numpy.ndarray'>
Array "c":  [1. 2. 4.]
Type array "c":  <class 'numpy.ndarray'>
Pen