Python NumPy Array:#

A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension.

Numpy array is a powerful N-dimensional array object which is in the form of rows and columns. We can initialize NumPy arrays from nested Python lists and access it elements.

NumPy Array Types:#

Create a NumPy Array#

Simplest way to create an array in Numpy is to use Python List

Load in NumPy Library#

import numpy as np
my_list = [1,2,3,4]
my_list
[1, 2, 3, 4]

To convert python list to a numpy array by using the object np.array.

numpy_array_from_list = np.array(my_list)
numpy_array_from_list
array([1, 2, 3, 4])

In practice, there is no need to declare a Python List. The operation can be combined.

my_list1  = np.array([1,2,3,4])
my_list1
array([1, 2, 3, 4])

NOTE: Numpy documentation states use of np.ndarray to create an array. However, this the recommended method

You can also create a numpy array from a Tuple

my_list2 = np.array (range (1,5))
my_list2
array([1, 2, 3, 4])

Numpy Array basics#

We can initialize numpy arrays from nested Python lists, and access elements using square brackets []:

a = np.array([1,2,3]) # Create a 1D array
print(a) 
print(type(a))  # Prints "<class 'numpy.ndarray'>"
[1 2 3]
<class 'numpy.ndarray'>
b = np.array([[9.0,8.0,7.0],[6.0,5.0,4.0]])
print(b)
[[9. 8. 7.]
 [6. 5. 4.]]
my_matrix = [[1,2,3],[4,5,6],[7,8,9]]
my_matrix
np.array(my_matrix)
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
# Get Dimension
a.ndim
1
# Get Shape
b.shape
(2, 3)
# Get Size
a.itemsize
4
# Get Size
b.itemsize
8
# Get total size
a.nbytes  # a.nbytes = a.size * a.itemsize
12
# Get number of elements
a.size
3
c = np.array([[True, False], [False, True]])
c
array([[ True, False],
       [False,  True]])
print(c.size)
print(c.shape) 
4
(2, 2)
a = np.array([1, 2, 3])   # Create a 1d array
print(a)
print(type(a))            # Prints "<class 'numpy.ndarray'>"
print(a.shape)            # Prints "(3,)"
print(a[0], a[1], a[2])   # Indexing with 3 elements. Prints "1 2 3"
a[0] = 5                  # Change an element of the array
print(a)                  # Prints "[5, 2, 3]"

b = np.array([[1,2,3],[4,5,6]])    # Create a 2d array
print(b)
print(b.shape)                     # Prints "(2, 3)"
print(b[0, 0], b[0, 1], b[1, 0])   # Prints "1 2 4"
[1 2 3]
<class 'numpy.ndarray'>
(3,)
1 2 3
[5 2 3]
[[1 2 3]
 [4 5 6]]
(2, 3)
1 2 4

Array datatypes#

Every numpy array is a grid of elements of the same type. Numpy provides a large set of numeric datatypes that you can use to construct arrays. The full list of NumPy datatype (dtypes) can be found in the NumPy documentation.

The two biggest things to remember are

  • Missing values (NaN) cast integer or boolean arrays to floats

  • NumPy arrays only have a single dtype for every element

  • the object dtype is the fallback

Numpy tries to guess a datatype when you create an array, but functions that construct arrays usually also include an optional argument to explicitly specify the datatype. For example:

a = np.array([1,2,3], dtype='int32') # Create a 1D array with int32 type
print(a) 
[1 2 3]
# Get Type
a.dtype
dtype('int32')
b = np.array([[9.0,8.0,7.0],[6.0,5.0,4.0]])
print(b)
b.dtype
[[9. 8. 7.]
 [6. 5. 4.]]
dtype('float64')
import numpy as np

x = np.array([1, 2])   # Let numpy choose the datatype
print(x.dtype)         # Prints "int64"

x = np.array([1.0, 2.0])   # Let numpy choose the datatype
print(x.dtype)             # Prints "float64"

x = np.array([1, 2], dtype=np.int64)   # Force a particular datatype
print(x.dtype)                         # Prints "int64"
int32
float64
int64
  • Does a NumPy array have a single dtype or multiple dtypes?

    • NumPy arrays are homogenous: they only have a single dtype (unlike DataFrames). You can have an array that holds mixed types, e.g. np.array(['a', 1]), but the dtype of that array is object, which you probably want to avoid.

You can read all about numpy datatypes in this documentation.

Random number#

rand#

Random values in a given shape from a uniform distribution over [0, 1)

np.random.rand(3)
array([0.22672978, 0.55283762, 0.10276143])
np.random.rand(3,5)
array([[0.2559205 , 0.60786967, 0.83770503, 0.45359369, 0.27764243],
       [0.38209653, 0.44225798, 0.63158859, 0.81893678, 0.79823164],
       [0.69791535, 0.69343173, 0.04763428, 0.1097501 , 0.30920635]])
# Random decimal numbers
np.random.rand(4,2)

#or
#np.random.random_sample(a.shape)
array([[0.55360672, 0.30668723],
       [0.93102691, 0.05082974],
       [0.23180804, 0.95966987],
       [0.68602648, 0.89632087]])

randn#

Return a sample (or samples) from the “standard normal” distribution. Not Uniform.with mean 0 and variance with 1.

np.random.randn(3)
array([-1.33142653,  1.54275813,  0.00616708])
np.random.randn(4,3)
array([[-2.85505447, -0.48048431, -1.98749888],
       [-0.43563027, -1.35266299, -0.65628077],
       [-0.40015831, -1.14770535,  0.61784629],
       [-1.27672348, -0.54777888,  1.51026454]])

randint#

Return random integers from low (inclusive) to high (exclusive).

np.random.randint(2,100)
85
# Random Integer values
np.random.randint(-4,8, size=(3,3))
array([[ 1,  2,  2],
       [ 5,  3,  2],
       [ 6, -1,  2]])
x = np.random.randint(0, 10, 10)
y = np.random.randint(0, 10, 10)
x, y
(array([9, 3, 3, 7, 5, 8, 4, 0, 0, 7]), array([2, 4, 7, 2, 5, 0, 7, 0, 9, 5]))

It’s also sometimes a more convinient way of writing and thinking about things.

[i + j for i, j in zip(x, y)]
[11, 7, 10, 9, 10, 8, 11, 0, 9, 12]
x + y
array([11,  7, 10,  9, 10,  8, 11,  0,  9, 12])

Array Attributes and Methods#

rana = np.random.randint(1,10,8)
rana
array([5, 9, 9, 2, 2, 3, 6, 1])

max, min, argmax, argmin#

rana
array([5, 9, 9, 2, 2, 3, 6, 1])
rana.max()
9
rana.argmax()
1
rana.min()
1
rana.argmin()
7

Numpy also provides many functions to create arrays:#

# Generating Zeros
np.zeros(5)
array([0., 0., 0., 0., 0.])
# All 0s matrix
np.zeros((2,3))  # pass a tupple
array([[0., 0., 0.],
       [0., 0., 0.]])
# Generating Zeros
np.ones(3)       # one function
array([1., 1., 1.])
np.ones(1)*5
array([5.])
np.ones((3,3))
array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])
# All 1s matrix
np.ones((4,2,2), dtype='int32')
array([[[1, 1],
        [1, 1]],

       [[1, 1],
        [1, 1]],

       [[1, 1],
        [1, 1]],

       [[1, 1],
        [1, 1]]])
# Any other number
np.full((2,2), 99)
array([[99, 99],
       [99, 99]])
# Any other number (full_like)
np.full_like(a, 4)

#or np.full(a.shape, 4)
array([4, 4, 4])
# The identity matrix
np.identity(5)
array([[1., 0., 0., 0., 0.],
       [0., 1., 0., 0., 0.],
       [0., 0., 1., 0., 0.],
       [0., 0., 0., 1., 0.],
       [0., 0., 0., 0., 1.]])
# Repeat an array
arr = np.array([[1,2,3]])
r1 = np.repeat(arr,3, axis=0)
print(r1)
[[1 2 3]
 [1 2 3]
 [1 2 3]]
import numpy as np

a = np.zeros((2,2))   # Create an array of all zeros
print(a)              # Prints "[[ 0.  0.]
                      #          [ 0.  0.]]"

b = np.ones((1,2))    # Create an array of all ones
print(b)              # Prints "[[ 1.  1.]]"

c = np.full((2,2), 7)  # Create a constant array
print(c)               # Prints "[[ 7.  7.]
                       #          [ 7.  7.]]"

d = np.eye(2)         # Create a 2x2 identity matrix
print(d)              # Prints "[[ 1.  0.]
                      #          [ 0.  1.]]"

e = np.random.random((2,2))  # Create an array filled with random values
print(e)                     # Might print "[[ 0.91940167  0.08143941]
                             #               [ 0.68744134  0.87236687]]"
[[0. 0.]
 [0. 0.]]
[[1. 1.]]
[[7 7]
 [7 7]]
[[1. 0.]
 [0. 1.]]
[[0.53909609 0.12336799]
 [0.93143051 0.39878883]]
#Generate matrix

# 1 1 1 1 1
# 1 0 0 0 1
# 1 0 9 0 1
# 1 1 1 1 1

output = np.ones((5,5))
print(output)

z = np.zeros((3,3))
z[1,1] = 9
print(z)

output[1:-1,1:-1] = z
print(output)
[[1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]]
[[0. 0. 0.]
 [0. 9. 0.]
 [0. 0. 0.]]
[[1. 1. 1. 1. 1.]
 [1. 0. 0. 0. 1.]
 [1. 0. 9. 0. 1.]
 [1. 0. 0. 0. 1.]
 [1. 1. 1. 1. 1.]]

You can read about other methods of array creation in this documentation.