Python NumPy Array

NumPy is the shorter version for Numerical Python. Numpy module is the foundation to introduce Data Science into Python. The Python NumPy package has built-in functions that are required to perform Data Analysis and Scientific Computing.

All the other packages that we use for data analysis built on top of this Python Numpy module. That’s why one has to master this Python Numpy module before start working with DataFrames or Data analysis.

Creating Python ndarray

The Python Numpy module has a ndarray object, shorter version of N-dimensional array, or an array. Like any other programming language array, this Python Numpy ndarray object allows you to store multiple array items of the same data type.

The following are the list of available functions to create an Array by the Python Numpy module.

  • array function: which helps you to create an array or convert the data from List, Tuple, or any sequence of items (something like range) to ndarray.
  • asarray function: Use this to convert the input data to Python ndarray. However, it won’t copy if the given input is already a ndarray.
  • zeros: Creates an array of 0’s of specified shape and type.
  • zeros_like: Same as zeros. However, it takes another array to get shape and dtype.
  • ones: Creates an array of 1’s of a given shape and data type.
  • ones_like: It accepts another array to read its shape and data type.
  • empty, empty_like: These functions create an empty array by allocating some memory to them.
  • arange: This creates or returns an array of elements in a given range. Same as range function.
  • eye, identity: creates a square identity matrix in Python.

Create an Array in Python using the array function

As we said earlier, the Python Numpy array function converts the given list, tuple, or any sequence for that matter into an array or ndarray. It is a simple example to create an array in Python.

import numpy as np
 
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
 
print(arr)

Python Numpy Array function output

[1 2 3 4 5 6 7 8 9]

Create an Array from List in Python

Here, we declared an integer list of numbers from 1 to 5. Next, we used the Python array function available in the numpy module to convert that list into an array or ndarray.

import numpy as np

a = [1, 2, 3, 4, 5]
arr = np.array(a)
 
print(arr)

Python Numpy Array from list items output

[1 2 3 4 5]

Let me create an ndarray of mixed items in Python.

import numpy as np
a = [2.5, 3.5, 7, 4.5, 8]
arr = np.array(a)
print(arr)

Python Numpy Mixed ndarray output

[2.5 3.5 7. 4.5 8. ]

Let me create a Python Numpy ndarray from a list of lists. Here, we declared a nested list of lists with integer values. Next, we used the array function to convert the list to Numpy array.

import numpy as np
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print('List of List = ', a)
print()
 
arr = np.array(a)
print(arr)

Python Numpy Array from list of lists output

List of List = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

[[1 2 3]
[4 5 6]
[7 8 9]]

You might wonder, why don’t we use Lists when it looks like the same?. Arrays meant to perform vectorized operations. I mean, when you perform any operation or use any function, then that function applied to each item in an array. 

We show those operations in the upcoming topic. However, we use a simple example to show you the same.

import numpy as np
a = [1, 2, 3, 4, 5]
arr = np.array(a)
  
print('Original Array      = ', arr)
print('Add 5 to Array      = ', arr + 5)
print('Multiply arr with 2 = ', arr * 2)

Vector operations on Python numpy ndarray output.

Original Array = [1 2 3 4 5]
Add 5 to Array = [ 6 7 8 9 10]
Multiply arr with 2 = [ 2 4 6 8 10]

Create an Array from Tuple

You can also create an array from a Tuple in Python.

import numpy as np

tup = (10, 20, 30)
arr = np.array(tup)

print(arr)

Python Tuple to Numpy Array output

[10 20 30]

Python NumPy Two Dimensional Array

Placing or Nesting two lists inside a [] brackets create a two-dimensional array.

import numpy as np
 
two_arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
 
print(two_arr)

Python Numpy two dimensional array output

[[ 1 2 3 4 5]
[ 6 7 8 9 10]]

Python NumPy Three Dimensional Array

Here, we are creating a 3 * 3 matrix or three-dimensional array.

import numpy as np
 
three_arr = np.array([[1, 2, 3], [10, 20, 30], [6, 7, 8]])
 
print(three_arr)

Python Numpy three dimensional array or Matrix output.

[[ 1 2 3]
[10 20 30]
[ 6 7 8]]

Create a Python Numpy Array using srange

In this example, we are using the Python Numpy arange function to create an array of numbers range from 0 to n-1, where n is the given number. For example, np.arange(5) retunes an array of numbers in sequence from 0 to 4.

import numpy as np

np.arange(5)
np.arange(10)
np.arange(15)

Python Numpy srange function to create ndarray output

>>> import numpy as np
>>> np.arange(5)
array([0, 1, 2, 3, 4])
>>> 
>>> np.arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> 
>>> np.arange(15)
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14])

Create an Array using linspace in Python

In this example, we used the Python Numpy linspace function to create a ndarray. The syntax behind this function is:

np.linspace(start, end_value, steps)

Here, we created three arrays of numbers range from 0 to n serrated by steps. For example, np.linspace(0, 1, 5) retunes an array of numbers from 0 to 1 in five equal steps.

import numpy as np

np.linspace(0, 1, 5)
np.linspace(0, 10, 5)

np.linspace(0, 1, 7)
np.linspace(10, 100, 20)

Python Numpy linespace function to create ndarray output

>>> import numpy as np
>>> np.linspace(0, 1, 5)
array([0.  , 0.25, 0.5 , 0.75, 1.  ])
>>> 
>>> np.linspace(0, 10, 5)
array([ 0. ,  2.5,  5. ,  7.5, 10. ])
>>> 
>>> np.linspace(0, 1, 7)
array([0.        , 0.16666667, 0.33333333, 0.5       , 0.66666667,
       0.83333333, 1.        ])
>>> 
>>> np.linspace(10, 100, 20)
array([ 10.        ,  14.73684211,  19.47368421,  24.21052632,
        28.94736842,  33.68421053,  38.42105263,  43.15789474,
        47.89473684,  52.63157895,  57.36842105,  62.10526316,
        66.84210526,  71.57894737,  76.31578947,  81.05263158,
        85.78947368,  90.52631579,  95.26315789, 100.        ])

Apart from an array function, the NumPy module has few other functions to create an ndarray. They are zeros, ones, and empty functions.

Python zeros array

The Python Numpy zeros function creates an array of zeros. This function accepts the arguments to specify the shape of an array. For example,

  • zeros(2) means a one-dimensional array of two zero elements.
  • zeros(2, 3) means 2 * 3 matrix of zeros.
  • and zeros(2, 3, 4) means a three-dimensional array of zeros.
import numpy as np
np.zeros(3)
np.zeros((2, 2))

np.zeros((2, 3))
np.zeros((4, 7))
np.zeros((3, 2, 7))

creating Numpy Array of zeros in Python output

>>> np.zeros(3)
array([0., 0., 0.])
>>> 
>>> np.zeros((2, 2))
array([[0., 0.],
       [0., 0.]])
>>> 
>>> np.zeros((2, 3))
array([[0., 0., 0.],
       [0., 0., 0.]])
>>> 
>>> np.zeros((4, 7))
array([[0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0.]])
>>> 
>>> np.zeros((3, 2, 7))
array([[[0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0.]],

       [[0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0.]],

       [[0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 0., 0.]]])

Python ones array

The Python ones function to create an array of 1’s. This numpy ones function accepts the arguments to specify the shape or number of items of an array. For example,

  • ones(4) means a one-dimensional array of four 1’s.
  • ones(2, 4) means 2 * 4 matrix of ones and ones(2, 3, 4) means 3D array 2 * 3 * 4 of 1’s.
import numpy as np

np.ones(5)
np.ones((3, 3))
np.ones((3, 5))
np.ones((3, 2, 9))

Python Numpy ndarray of ones output

>>> import numpy as np
>>> np.ones(5)
array([1., 1., 1., 1., 1.])
>>> 
>>> np.ones((3, 3))
array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])
>>> 
>>> np.ones((3, 5))
array([[1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.]])
>>> 
>>> np.ones((3, 2, 9))
array([[[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., 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., 1., 1., 1., 1.]]])

Python Numpy random array

Use the Python NumPy random function to create an array of random numbers. Please visit Python Random Array article

import numpy as np

np.random.random(5)
np.random.random((4, 4))
np.random.random((2, 3, 4))

Python Numpy random ndarray output

>>> import numpy as np
>>> np.random.random(5)
array([0.17481245, 0.20246847, 0.95714739, 0.93449316, 0.00816149])
>>> 
>>> np.random.random((4, 4))
array([[0.19520415, 0.73605745, 0.27957035, 0.39129715],
       [0.3622134 , 0.10631005, 0.29756787, 0.49672655],
       [0.32448671, 0.53070647, 0.09666927, 0.9382703 ],
       [0.77069343, 0.75228313, 0.65435786, 0.13130023]])
>>> 
>>> np.random.random((2, 3, 4))
array([[[0.13560378, 0.41655648, 0.60812992, 0.87341762],
        [0.82085101, 0.02908754, 0.1446217 , 0.1984121 ],
        [0.97777709, 0.95961773, 0.75990116, 0.87158335]],

       [[0.88883459, 0.55730694, 0.45067219, 0.89653719],
        [0.39533872, 0.63479585, 0.23116183, 0.56565847],
        [0.25483409, 0.7929711 , 0.80572657, 0.19862024]]])

Python empty array

The Python empty function creates an empty array. It is not always an empty array, and it might load garbage values or zeros, etc. So, don’t be surprised!.

import numpy as np
np.empty(3)
np.empty((2, 3))
np.empty((2, 4))
np.empty((2, 3, 5))

Python Numpy empty array or ndarray output

>>> import numpy as np
>>> np.empty(3)
array([3., 2., 1.])
>>> np.empty((2, 3))
array([[4.33404091e-311, 1.97626258e-323, 1.20871698e-315],
       [2.14187885e-296, 8.58539581e-210, 6.25613152e-309]])
>>> np.empty((2, 4))
array([[-0.00000000e+000,  4.33404091e-311,  1.97626258e-323,
                     nan],
       [ 1.20871698e-315,  2.14187885e-296, -8.58539581e-210,
         6.25613152e-309]])
>>> np.empty((2, 3, 5))
array([[[-0.00000000e+000, -0.00000000e+000, -7.90505033e-323,
          0.00000000e+000,  2.12199579e-314],
        [ 0.00000000e+000,  0.00000000e+000,  0.00000000e+000,
          1.77229088e-310,  3.50977866e+064],
        [ 0.00000000e+000,  0.00000000e+000,              nan,
                      nan,  3.50977942e+064]],

       [[ 0.00000000e+000, -0.00000000e+000, -0.00000000e+000,
         -3.95252517e-323,  0.00000000e+000],
        [ 2.12199579e-314,  0.00000000e+000,  0.00000000e+000,
          0.00000000e+000,  1.77229088e-310],
        [ 3.50977866e+064,  0.00000000e+000,  0.00000000e+000,
                      nan,              nan]]])

Python full array

The NumPy full function creates an array of a given number.

import numpy as np

# Returns one dimensional array of 4’s of size 5
np.full((5), 4)

# Returns 3 * matrix of number 9
np.full((3, 4), 9)
np.full((4, 4), 8)
np.full((2, 3, 6), 7)

Python Numpy full array or ndarray output

>>> import numpy as np
>>> np.full((5), 4)
array([4, 4, 4, 4, 4])
>>> 
>>> np.full((3, 4), 9)
array([[9, 9, 9, 9],
       [9, 9, 9, 9],
       [9, 9, 9, 9]])
>>> np.full((4, 4), 8)
array([[8, 8, 8, 8],
       [8, 8, 8, 8],
       [8, 8, 8, 8],
       [8, 8, 8, 8]])
>>> np.full((2, 3, 6), 7)
array([[[7, 7, 7, 7, 7, 7],
        [7, 7, 7, 7, 7, 7],
        [7, 7, 7, 7, 7, 7]],

       [[7, 7, 7, 7, 7, 7],
        [7, 7, 7, 7, 7, 7],
        [7, 7, 7, 7, 7, 7]]])

Python identical array

The Python eye function creates an identical N * N matrix, where N is the given argument value.

import numpy as np
np.eye(2)
np.eye(3)
np.eye(5)

Python Numpy Identical Arrays output

>>> import numpy as np
>>> np.eye(2)
array([[1., 0.],
       [0., 1.]])
>>> 
>>> np.eye(3)
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
>>> 
>>> np.eye(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.]])

Python diagonal array

The Python diag function creates an identical array or ndarray, where diagonal values filled with the list values.

import numpy as np
np.diag([3])
np.diag([1, 2])
np.diag([1, 2, 3, 4])
np.diag([1, 2, 3, 4, 5, 6])

Python Numpy diagonal ndarray output

>>> import numpy as np
>>> np.diag([3])
array([[3]])
>>> 
>>> np.diag([1, 2])
array([[1, 0],
       [0, 2]])
>>> 
>>> np.diag([1, 2, 3, 4])
array([[1, 0, 0, 0],
       [0, 2, 0, 0],
       [0, 0, 3, 0],
       [0, 0, 0, 4]])
>>> 
>>> np.diag([1, 2, 3, 4, 5, 6])
array([[1, 0, 0, 0, 0, 0],
       [0, 2, 0, 0, 0, 0],
       [0, 0, 3, 0, 0, 0],
       [0, 0, 0, 4, 0, 0],
       [0, 0, 0, 0, 5, 0],
       [0, 0, 0, 0, 0, 6]])

Accessing Numpy Array Items

We can access the array items using the index position. The index position always starts at 0 and ends at n-1, where n is the array size, row size, or column size, or dimension. Access the items from one-dimensional array.

import numpy as np
arr = np.array([10, 15, 25, 35, 45, 55, 65])
arr

arr[0]
arr[2]
arr[5]
arr[7]
arr[2:5]

Output of accessing the Numpy one dimensional ndarray items

>>> import numpy as np
>>> arr = np.array([10, 15, 25, 35, 45, 55, 65])
>>> arr
array([10, 15, 25, 35, 45, 55, 65])
>>> 
>>> arr[0]
10
>>> arr[2]
25
>>> arr[5]
55
>>> arr[7]
Traceback (most recent call last):
  File "<pyshell#165>", line 1, in <module>
    arr[7]
IndexError: index 7 is out of bounds for axis 0 with size 7
>>> arr[2:5]
array([25, 35, 45])

As you can see, the last but one statement is throwing an error (index out of range) because n-1 (7-1) is the last index value we have. We used arr[2:5], which returns a portion of an array to view. It’s called slicing.

This example shows how to access the two-dimensional array items using indexes.

import numpy as np
arr = np.array([[1, 2, 3, 4, 5],[12, 15, 61, 11, 19]])
arr[0][1]
arr[0][4]
arr[1][1]
arr[1][4]

Output of accessing Numpy two dimensional ndarray items

>>> import numpy as np
>>> arr = np.array([[1, 2, 3, 4, 5],[12, 15, 61, 11, 19]])
>>> arr
array([[ 1,  2,  3,  4,  5],
       [12, 15, 61, 11, 19]])
>>> arr[0][1]
2
>>> 
>>> arr[0][4]
5
>>> arr[1][1]
15
>>> arr[1][4]
19

Alter Numpy Array Items

Same as accessing array items, you can alter numpy array items using the index position. It is an example to access the items from a one-dimensional array.

import numpy as np
a = np.array([10, 20, 30, 40, 50])
a
 
a[0] = 150
a
 
a[3] = 111
a
 
b = np.array([[10, 50, 100], [250, 500, 1000]])
b

b[0, 0] = 99
b

b[1, 1] = 222
b

b[1, 2] = 444
b

Output of altering the numpy ndarray items

>>> import numpy as np
>>> a = np.array([10, 20, 30, 40, 50])
>>> a
array([10, 20, 30, 40, 50])
>>> a[0] = 150
>>> a
array([150,  20,  30,  40,  50])
>>> 
>>> a[3] = 111
>>> a
array([150,  20,  30, 111,  50])
>>> 
>>> b = np.array([[10, 50, 100], [250, 500, 1000]])
>>> b
array([[  10,   50,  100],
       [ 250,  500, 1000]])
>>> b[0, 0] = 99
>>> b
array([[  99,   50,  100],
       [ 250,  500, 1000]])
>>> b[1, 1] = 222
>>> b
array([[  99,   50,  100],
       [ 250,  222, 1000]])
>>> 
>>> b[1, 2] = 444
>>> b
array([[ 99,  50, 100],
       [250, 222, 444]])

Python Numpy array Slicing

First, we declare a single or one-dimensional array and slice that array. Python slicing accepts an index position of start and endpoint of an array. The syntax of this is array_name[Start_poistion, end_posiition].

Both the start and end position has default values as 0 and n-1(maximum array length). For example, arr1[1:5] means starts at index position 1 and ends at position 5. arr1[:7] starts at 0 and ends at index position 7.

arr1 = np.array([10, 25, 50, 75, 100, 125, 150, 200, 250])
arr1

arr1[1:5]
arr1[2:7]
arr1[4:8]
arr1[3:9]

arr1[3:]
arr1[:7]

Python One dimensional Numpy ndarray slicing output

>>> import numpy as np
>>> arr1 = np.array([10, 25, 50, 75, 100, 125, 150, 200, 250])
>>> arr1
array([ 10,  25,  50,  75, 100, 125, 150, 200, 250])
>>> arr1[1:5]
array([ 25,  50,  75, 100])
>>> arr1[2:7]
array([ 50,  75, 100, 125, 150])
>>> arr1[4:8]
array([100, 125, 150, 200])
>>> arr1[3:9]
array([ 75, 100, 125, 150, 200, 250])
>>> arr1[3:]
array([ 75, 100, 125, 150, 200, 250])
>>> arr1[:7]
array([ 10,  25,  50,  75, 100, 125, 150])

This time, we declared a two-dimensional array and slicing the same using index values.

arr2 = np.array([[26, 48, 91, 57, 120], [33, 95, 68, 109, 155],
                [111, 194, 7, 22, 124], [ 82, 119, 18, 156, 81],
                [ 38, 10, 151, 24, 14]])
arr2
 
arr2[:2, :2]
arr2[:3, :4]

arr2[:3, ]
arr2[:3]
arr2[:4]
arr2[:,:4]

Python Two Dimensional numpy ndarray slicing output

>>> import numpy as np
>>> arr2 = np.array([[26, 48, 91, 57, 120], [33, 95, 68, 109, 155],
                [111, 194, 7, 22, 124], [ 82, 119, 18, 156, 81],
                [ 38, 10, 151, 24, 14]])
>>> arr2
array([[ 26,  48,  91,  57, 120],
       [ 33,  95,  68, 109, 155],
       [111, 194,   7,  22, 124],
       [ 82, 119,  18, 156,  81],
       [ 38,  10, 151,  24,  14]])
>>> arr2[:2, :2]
array([[26, 48],
       [33, 95]])
>>> arr2[:3, :4]
array([[ 26,  48,  91,  57],
       [ 33,  95,  68, 109],
       [111, 194,   7,  22]])
>>> arr2[:3, ]
array([[ 26,  48,  91,  57, 120],
       [ 33,  95,  68, 109, 155],
       [111, 194,   7,  22, 124]])
>>> arr2[:3]
array([[ 26,  48,  91,  57, 120],
       [ 33,  95,  68, 109, 155],
       [111, 194,   7,  22, 124]])
>>> arr2[:4]
array([[ 26,  48,  91,  57, 120],
       [ 33,  95,  68, 109, 155],
       [111, 194,   7,  22, 124],
       [ 82, 119,  18, 156,  81]])
>>> arr2[:,:4]
array([[ 26,  48,  91,  57],
       [ 33,  95,  68, 109],
       [111, 194,   7,  22],
       [ 82, 119,  18, 156],
       [ 38,  10, 151,  24]])

Slicing Numpy ndarray with Negative Values

From the above arrays, let me use the negative values as the start and end positions.

arr1[:3]
arr1[:-4]
arr1[-4:]
 
arr2[:-2, :-1]
arr2[:-3, :-1]
arr2[:-2,]
arr2[:-3,]
 
arr2[:,:-3]
arr2[:,:-2]

Negative values to slice Numpy Array output

>>> import numpy as np
>>> arr1 = np.array([10, 25, 50, 75, 100, 125, 150, 200, 250])
>>> arr2 = np.array([[26, 48, 91, 57, 120], [33, 95, 68, 109, 155],
                [111, 194, 7, 22, 124], [ 82, 119, 18, 156, 81],
                [ 38, 10, 151, 24, 14]])
>>> arr1[:3]
array([10, 25, 50])
>>> arr1[:-4]
array([ 10,  25,  50,  75, 100])
>>> arr1[-4:]
array([125, 150, 200, 250])
>>> arr2[:-2, :-1]
array([[ 26,  48,  91,  57],
       [ 33,  95,  68, 109],
       [111, 194,   7,  22]])
>>> arr2[:-3, :-1]
array([[ 26,  48,  91,  57],
       [ 33,  95,  68, 109]])
>>> arr2[:-3,]
array([[ 26,  48,  91,  57, 120],
       [ 33,  95,  68, 109, 155]])
>>> 
>>> arr2[:,:-3]
array([[ 26,  48],
       [ 33,  95],
       [111, 194],
       [ 82, 119],
       [ 38,  10]])
>>> arr2[:,:-2]
array([[ 26,  48,  91],
       [ 33,  95,  68],
       [111, 194,   7],
       [ 82, 119,  18],
       [ 38,  10, 151]])

Reverse Numpy array in Python

Using the negative index value, you can reverse rows and column position of values, which is called Python Numpy array reverse.

import numpy as np
arr1 = np.array([10, 50, 100, 150, 250])

arr2 = np.array([[26, 48, 91, 57, 120], [33, 95, 68, 109, 155],
                [111, 194, 7, 22, 124], [ 82, 119, 18, 156, 81],
                [ 38, 10, 151, 24, 14]])
 
arr1[::-1]
# Reverse the row position only
arr2[::-1,]
 
# Reverse both the row and column position
arr2[::-1, ::-1]

Output of Reversed Numpy ndarray in Python

>>> import numpy as np
>>> arr1 = np.array([10, 50, 100, 150, 250])
>>> arr2 = np.array([[26, 48, 91, 57, 120], [33, 95, 68, 109, 155],
                [111, 194, 7, 22, 124], [ 82, 119, 18, 156, 81],
                [ 38, 10, 151, 24, 14]])
>>> arr1
array([ 10,  50, 100, 150, 250])
>>> arr2
array([[ 26,  48,  91,  57, 120],
       [ 33,  95,  68, 109, 155],
       [111, 194,   7,  22, 124],
       [ 82, 119,  18, 156,  81],
       [ 38,  10, 151,  24,  14]])
>>> arr1[::-1]
array([250, 150, 100,  50,  10])
>>> arr2[::-1,]
array([[ 38,  10, 151,  24,  14],
       [ 82, 119,  18, 156,  81],
       [111, 194,   7,  22, 124],
       [ 33,  95,  68, 109, 155],
       [ 26,  48,  91,  57, 120]])
>>> arr2[::-1, ::-1]
array([[ 14,  24, 151,  10,  38],
       [ 81, 156,  18, 119,  82],
       [124,  22,   7, 194, 111],
       [155, 109,  68,  95,  33],
       [120,  57,  91,  48,  26]])

Create an Array from existing Array

This example shows how to create an array from an existing array in Python. For this, we are using the Python Numpy array slicing concept.

arr3 = arr1[2:7]
arr3
 
arr4 = arr1[3:]
arr4
 
arr5 = arr2[::-1,]
arr5
 
arr6 = arr2[::-1, ::-1]
arr6

Creating an array using numpy ndarray slicing technique output

>>> import numpy as np
>>> arr1 = np.array([10, 50, 100, 150, 250])
>>> arr2 = np.array([[26, 48, 91, 57, 120], [33, 95, 68, 109, 155],
                [111, 194, 7, 22, 124], [ 82, 119, 18, 156, 81],
                [ 38, 10, 151, 24, 14]])
>>> arr3 = arr1[2:7]
>>> arr3
array([100, 150, 250])
>>> arr4 = arr1[3:]
>>> arr4
array([150, 250])
>>> arr5 = arr2[::-1,]
>>> arr5
array([[ 38,  10, 151,  24,  14],
       [ 82, 119,  18, 156,  81],
       [111, 194,   7,  22, 124],
       [ 33,  95,  68, 109, 155],
       [ 26,  48,  91,  57, 120]])
>>> arr6 = arr2[::-1, ::-1]
>>> arr6
array([[ 14,  24, 151,  10,  38],
       [ 81, 156,  18, 119,  82],
       [124,  22,   7, 194, 111],
       [155, 109,  68,  95,  33],
       [120,  57,  91,  48,  26]])

Python Numpy array Boolean index

The boolean index in Python Numpy ndarray object is an important part to notice. You can use this boolean index to check whether each item in an array with a condition.

First, x = arr1 > 40 returns an array of boolean true and false based on the condition (arr1 > 40). I mean, if a value is greater than 40 True otherwise, False. Next, arr1[x] returns an array of a sequence whose value is greater than 40. The same applies to multi-Dimensional arrays.

import numpy as np
 
arr1 = np.array([10, 20, 50, 90, 5, 40, 60, 30, 25])
x = arr1 > 40
print("Array            : ", arr1)
print("Array Bool index : ", x)
print("Array            : ", arr1[x])
 
y = arr1 < 40
print("Array Bool index : ", y)
print("Array            : ", arr1[y])
 
arr2 = np.array(np.random.randint(1, 10, size = (3, 8)))
z = arr2 > 4 
print("-----Array2------\n", arr2)
print("------Array2 Bool index------\n", z)
print("------Array2------\n", arr2[z])

Python Numpy ndarray Boolean Index output

Array : [10 20 50 90 5 40 60 30 25]
Array Bool index : [False False True True False False True False False]
Array : [50 90 60]
Array Bool index : [ True True False False True False False True True]
Array : [10 20 5 30 25]
----- Array2 ------
[[3 1 5 9 9 8 9 9]
[7 8 8 6 6 7 5 3]
[8 8 2 6 8 2 2 8]]
------ Array2 Bool index ------
[[False False True True True True True True]
[ True True True True True True True False]
[ True True False True True False False True]]
------ Array2 ------
[5 9 9 8 9 9 7 8 8 6 6 7 5 8 8 6 8 8]

Replace infinity and NaN values in a Python array

Replacing Not a Number and infinity values in a Python ndarray with exact numbers or values. Here, we declared 1D and 2D array with random values. Next, we replaced infinity and Nan with 11.56 and 29.16.

import numpy as np

arr1 = np.array([10, 20, 50, 90, 5, 40, 60, 30, 25], dtype = 'float')
print("Array            : ", arr1)

arr1[2] = np.nan
arr1[4] = np.inf
print("Array            : ", arr1)

# Replace inf and nan With 11.56
x = np.isinf(arr1) | np.isnan(arr1)
arr1[x] = 11.56
print("Array            : ", arr1)

arr2 = np.array( [[9, 7, np.nan, 8, np.inf],
                  [np.nan, 3, 7, np.inf, 5],
                  [8, np.inf, 4, np.nan, 1]],
                 dtype = 'float')
print("-----Array2------\n", arr2)

# Replace inf and nan in arr2 With 29.16
y = np.isinf(arr2) | np.isnan(arr2)
arr2[y] = 29.16
print("------Array2------\n", arr2)

Output of replacing NaN and Infinity values of Python ndarray

Array            :  [10. 20. 50. 90.  5. 40. 60. 30. 25.]
Array            :  [10. 20. nan 90. inf 40. 60. 30. 25.]
Array            :  [10.   20.   11.56 90.   11.56 40.   60.   30.   25.  ]
-----Array2------
 [[ 9.  7. nan  8. inf]
 [nan  3.  7. inf  5.]
 [ 8. inf  4. nan  1.]]
------Array2------
 [[ 9.    7.   29.16  8.   29.16]
 [29.16  3.    7.   29.16  5.  ]
 [ 8.   29.16  4.   29.16  1.  ]]

Arithmetic Operations on Python Numpy Array

Python Numpy allows you to perform arithmetic operations on an array using Arithmetic Operators. This example shows how to add, subtract, and multiply values on 1D, 2D, and multi-dimensional array.

arr = np.array([10, 15, 25, 35, 45, 55, 65])
arr
 
arr + 4
arr - 8
arr * 3
 
two_arr = np.array([[1, 2, 3, 4, 5],[12, 15, 61, 11, 19]])
two_arr
 
two_arr + 10
two_arr - 3
two_arr * 2
 
three_arr = np.array([[1, 2, 3], [10, 20, 30], [6, 7, 8]])
three_arr + 2
three_arr - 5
three_arr * 5

Python Numpy ndarray arithmetic operations output

>>> import numpy as np
>>> arr = np.array([10, 15, 25, 35, 45, 55, 65])
>>> arr
array([10, 15, 25, 35, 45, 55, 65])
>>> arr + 4
array([14, 19, 29, 39, 49, 59, 69])
>>> arr - 8
array([ 2,  7, 17, 27, 37, 47, 57])
>>> arr * 3
array([ 30,  45,  75, 105, 135, 165, 195])
>>> 
>>> two_arr = np.array([[1, 2, 3, 4, 5],[12, 15, 61, 11, 19]])
>>> two_arr
array([[ 1,  2,  3,  4,  5],
       [12, 15, 61, 11, 19]])
>>> two_arr + 10
array([[11, 12, 13, 14, 15],
       [22, 25, 71, 21, 29]])
>>> two_arr - 3
array([[-2, -1,  0,  1,  2],
       [ 9, 12, 58,  8, 16]])
>>> two_arr * 2
array([[  2,   4,   6,   8,  10],
       [ 24,  30, 122,  22,  38]])
>>> 
>>> three_arr = np.array([[1, 2, 3], [10, 20, 30], [6, 7, 8]])
>>> three_arr + 2
array([[ 3,  4,  5],
       [12, 22, 32],
       [ 8,  9, 10]])
>>> three_arr - 5
array([[-4, -3, -2],
       [ 5, 15, 25],
       [ 1,  2,  3]])
>>> three_arr * 5
array([[  5,  10,  15],
       [ 50, 100, 150],
       [ 30,  35,  40]])

Python ndarray Objects

The following Numpy ndarray objects help to find the information about an array.

  • ndim: Returns the Array dimension. If it is a one-dimensional array, then 1, two-dimensional array = 2, etc.
  • size: It displays or returns the number of elements or items in an array.
  • flags: Information about the memory layout of an array.
  • itemsize: Length of a numpy array in bytes.
  • nbytes: Total number of bytes consumed by an array.

The following Python Numpy Array example shows the same

import numpy as np
a = np.array([10, 50, 100, 150, 250])
 
b = np.array([[26, 48, 91, 57, 120], [33, 95, 68, 109, 155],
             [111, 194, 7, 22, 124], [ 82, 119, 18, 156, 81],
             [38, 10, 151, 24, 14]])
 
print('Array Dimension = ', a.ndim)
print('No of Elements in an Array = ', a.size)
print('Array Memory Layout = ', a.flags)
print('Array Length in Bytes = ', a.itemsize)
print('Total bytes consumed by an Array = ', a.nbytes)
 
print('\nArray Dimension = ', b.ndim)
print('No of Elements in an Array = ', b.size)
print('Array Memory Layout = ', b.flags)
print('Array Length in Bytes = ', b.itemsize)
print('Total bytes consumed by an Array = ', b.nbytes)

Python Numpy ndarray or array Objects output

Array Dimension =  1
No of Elements in an Array =  5
Array Memory Layout =    C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

Array Length in Bytes =  8
Total bytes consumed by an Array =  40

Array Dimension =  2
No of Elements in an Array =  25
Array Memory Layout =    C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

Array Length in Bytes =  8
Total bytes consumed by an Array =  200

Python ndarray shape

Python ndarray shape object is useful to display the array shape precisely, array dimensions.

  • If it is one dimensional, it returns the number of items.
  • If it is two dimensional, returns the rows, columns. Generally, Python assigns a proper data type to an array that we create. However, the Python array function also allows you to specify the data type of an array explicitly using dtype. Using this dtype object, either you can see the data type assigned to an array implicitly or can assign your own data type explicitly.

In this numpy array example, we created a 1d array, two-dimensional array, and three-dimensional array. Next, we are using this Python Numpy array shape object to return their matrix shapes.

import numpy as np
arr1 = np.array([10, 50, 100, 150, 250])
 
arr2 = np.array([[26, 48, 91, 57, 120], [33, 95, 68, 109, 155],
                [111, 194, 7, 22, 124], [ 82, 119, 18, 156, 81],
                [ 38, 10, 151, 24, 14]])
 
arr3 = np.array([[12, 11, 0, 9, 7], [10, 4, 11, 6, 9],
                [9, 2, 10, 9, 11], [ 5, 14, 0, 11, 8]])
 
print("Array 1.      : ", arr1)
print("Array 1 Shape : ", arr1.shape)
 
print("Array 2       : \n", arr2)
print("Array 2 Shape : ", arr2.shape)
 
print("Array 3       : \n", arr3)
print("Array 3 Shape : ", arr3.shape)

Numpy ndarray shape output

Array 1.      :  [ 10  50 100 150 250]
Array 1 Shape :  (5,)
Array 2       : 
 [[ 26  48  91  57 120]
 [ 33  95  68 109 155]
 [111 194   7  22 124]
 [ 82 119  18 156  81]
 [ 38  10 151  24  14]]
Array 2 Shape :  (5, 5)
Array 3       : 
 [[12 11  0  9  7]
 [10  4 11  6  9]
 [ 9  2 10  9 11]
 [ 5 14  0 11  8]]
Array 3 Shape :  (4, 5)

Python ndarray dtype

Generally, Python assigns a proper data type to an array that we create. However, the Python array function also allows you to specify the data type of an array explicitly using dtype. Using this dtype object, either you can see the data type assigned to an array implicitly or can assign your own data type explicitly.

List of available data types to create a Python ndarray.

Data TypeDescriptionData Type Code
int8Signed 8 bit integer typei1
uint8Unsigned 8 bit integer typeu1
int16, uint16Signed and Unsigned 16 bit integer typesi2, u2
int32, uint32Signed & Unsigned 32 bit integer typesi4, u4
int64, uint64Signed & Unsigned 64-bit integer typesi8, u8
float16Half Precision floating pointf2
float32Single Precision floating pointf4 or f
float64Double Precision floating pointf8 or d
float128Extended Precision floating pointf16 or g
complex64, complex128, complex256Complex numbers represented by 32, 64, 128 etcc8, c16, c32
boolBoolean True or False Type?
objectObject TypeO
string_String type. You have to specify the string length (no of characters). For example, 5 characters mean S5S
unicode_Unicode Type. You have to specify the number of bytes. For example, 10 means U10.U

In this Python example, we are creating two ndarrays. First, we create an array of integers and an array of mixed values (float and integer). Finally, we find their data types using dtype property.

import numpy as np
 
arr1 = np.array([10, 20, 30, 40, 50])
 
print("Array           : ", arr1)
print("Array Data Type : ", arr1.dtype)
 
arr2 = np.array([1, 3.10, 4.60, 5, 7.96])
 
print("\nArray         : ", arr2)
print("Array Data Type : ", arr2.dtype)
Array           :  [10 20 30 40 50]
Array Data Type :  int64

Array         :  [1.   3.1  4.6  5.   7.96]
Array Data Type :  float64

The Numpy dtype property is not about finding the Array data type. We can use this property to create an array of our own data types.

import numpy as np
 
list1 = [10, 20, 30, 40, 50]
 
arr1 = np.array(list1, dtype = 'int')
  
print("Array           : ", arr1)
print("Array Data Type : ", arr1.dtype)
 
arr2 = np.array(list1, dtype = 'float')
print("Array2           : ", arr2)
print("Array2 Data Type : ", arr2.dtype)
 
arr3 = np.array(list1, dtype = 'float16')
print("Array3           : ", arr3)
print("Array3 Data Type : ", arr3.dtype)

Numpy Array dtype property output

Array           :  [10 20 30 40 50]
Array Data Type :  int64
Array2           :  [10. 20. 30. 40. 50.]
Array2 Data Type :  float64
Array3           :  [10. 20. 30. 40. 50.]
Array3 Data Type :  float16

A few more Python examples to create a Numpy array of our own data type using dtype

import numpy as np
 
list1 = [1, 20, 0, 40, 0]
 
arr1 = np.array(list1, dtype = 'S')
print("Array           : ", arr1)
print("Array Data Type : ", arr1.dtype)
 
arr2 = np.array(list1, dtype = 'bool')
print("Array2           : ", arr2)
print("Array2 Data Type : ", arr2.dtype)
 
arr3 = np.array([1, 10, 'e', 'o', 9, 'Hi', 7], dtype = 'object')
print("Array3           : ", arr3)
print("Array3 Data Type : ", arr3.dtype)

Numpy ndarray dtype properties output

Array           :  [b'1' b'20' b'0' b'40' b'0']
Array Data Type :  |S2
Array2           :  [ True  True False  True False]
Array2 Data Type :  bool
Array3           :  [1 10 'e' 'o' 9 'Hi' 7]
Array3 Data Type :  object

Python ndarray reshape

The Python Numpy reshape function helps to reshape or change the size of an array as per your requirement. Here, First, we are changing single dimensional array to two-dimensional array. Next, we changed the shape to 4 * 3, and 2 * 6.

import numpy as np
 
arr1 = np.array([10, 20, 30, 40, 50, 60, 70, 80])
print("Array            : ", arr1)
 
x = arr1.reshape(2, 4)
print("------New Array 2 * 4------\n", x)
 
y = arr1.reshape(4, 2)
print("------New Array 4 * 2------\n", y)
 
arr2 = np.array( np.random.randint(1, 9, size = (3, 4)))
print("-----Array2------\n", arr2)
 
a = arr2.reshape(4, 3)
print("------New Array2 4 * 3------\n", a)
 
b = arr2.reshape(2, 6)
print("------New Array2 2 * 6------\n", b)

Numpy ndarray reshape function output

Array            :  [10 20 30 40 50 60 70 80]
------New Array 2 * 4------
 [[10 20 30 40]
 [50 60 70 80]]
------New Array 4 * 2------
 [[10 20]
 [30 40]
 [50 60]
 [70 80]]
-----Array2------
 [[6 2 5 5]
 [8 6 2 1]
 [4 3 1 8]]
------New Array2 4 * 3------
 [[6 2 5]
 [5 8 6]
 [2 1 4]
 [3 1 8]]
------New Array2 2 * 6------
 [[6 2 5 5 8 6]
 [2 1 4 3 1 8]]

Python Numpy flatten and ravel

Both Python Numpy flattens, and ravel functions flatten or converts any size to a single dimensional array. Although both are the same, the ravel function holds the reference of an actual array. It means any changes made to ravel output also reflect the original. However, this is not the same as the flatten function.

import numpy as np
 
arr1 = np.array(np.random.randint(1, 20, size = (3, 6)))
print("-----Array------\n", arr1)
 
x = arr1.flatten()
print("------flatten Array------\n", x)
 
y = arr1.ravel()
print("------ravel Array------\n", y)
 
arr2 = np.array(np.random.randint(10, 30, size = (2, 3, 4)))
print("-----Array2------\n", arr2)
 
a = arr2.flatten()
print("------flatten Array2------\n", a)
 
b = arr2.ravel()
print("------ravel Array2------\n", b)

Numpy Array flatten and ravel functions output

-----Array------
 [[ 7 15  5 11 18  9]
 [17 19  6  6 19  5]
 [10  7  6  8 13  7]]
------flatten Array------
 [ 7 15  5 11 18  9 17 19  6  6 19  5 10  7  6  8 13  7]
------ravel Array------
 [ 7 15  5 11 18  9 17 19  6  6 19  5 10  7  6  8 13  7]
-----Array2------
 [[[15 19 15 14]
  [11 20 23 19]
  [22 29 26 12]]

 [[13 12 18 27]
  [17 23 18 27]
  [14 25 12 16]]]
------flatten Array2------
 [15 19 15 14 11 20 23 19 22 29 26 12 13 12 18 27 17 23 18 27 14 25 12 16]
------ravel Array2------
 [15 19 15 14 11 20 23 19 22 29 26 12 13 12 18 27 17 23 18 27 14 25 12 16]

How to find Unique Items in a Python ndarray?

The Python Numpy module has a unique function used to find and return the unique values from a given 1D, 2D, and 3 Dimensional arrays.

import numpy as np
 
arr = np.random.randint(0, 5, size = 10)
print('Original Array = ', arr)
 
uniq = np.unique(arr)
print('Unique Items in arr = ', uniq)
 
arr2 = np.random.randint(10, 100, size = (3, 5))
print('\n---Two Dimensional Random Original Array----\n', arr2)
 
uniq2 = np.unique(arr2)
print('Unique Items in arr2 = ', uniq2)
 
arr3 = np.random.randint(15, 25, size = (2, 3, 8))
print('\n----Three Dimensional Random Original Array----\n', arr3)
 
uniq3 = np.unique(arr3)
print('Unique Items in arr3 = ', uniq3)

Unique Items in Numpy ndarray output

Original Array = [0 3 4 3 0 4 4 0 0 0]
Unique Items in arr = [0 3 4]

---Two Dimensional Random Original Array----
[[73 98 42 59 96]
[97 86 20 69 52]
[91 98 76 48 41]]
Unique Items in arr2 = [20 41 42 48 52 59 69 73 76 86 91 96 97 98]

----Three Dimensional Random Original Array----
[[[19 21 19 24 19 15 20 20]
[24 20 19 19 21 21 16 17]
[22 23 23 16 23 20 18 17]]

[[24 23 23 21 18 19 17 21]
[15 21 22 18 16 17 24 23]
[17 15 21 19 20 15 15 15]]]
Unique Items in arr3 = [15 16 17 18 19 20 21 22 23 24]

Count unique items in a Python ndarray

Count the total number of times each item repeated in a Python Numpy array. For this, you have to use the Numpy unique function with the return_counts parameter. If we set this parameter value to True, then it counts items.

import numpy as np
 
arr = np.random.randint(0, 5, size = 10)
print('Original Array = ', arr)
 
uniq, cnt = np.unique(arr, return_counts = True)
print('Unique Items in arr = ', uniq)
print('Count Items in arr = ', cnt)
 
arr2 = np.random.randint(10, 100, size = (3, 5))
print('\n---Two Dimensional Random Original Array----\n', arr2)
 
uniq2, cnt2 = np.unique(arr2, return_counts = True)
print('Unique Items in arr2 = ', uniq2)
print('Count Items in arr2 = ', cnt2)
 
arr3 = np.random.randint(15, 25, size = (2, 3, 8))
print('\n----Three Dimensional Random Original Array----\n', arr3)
 
uniq3, cnt3 = np.unique(arr3, return_counts = True)
print('Unique Items in arr3 = ', uniq3)
print('Count Items in arr3 = ', cnt3)

Count of Unique items in a Numpy Array output

Original Array = [0 1 1 0 2 4 2 3 4 0]
Unique Items in arr = [0 1 2 3 4]
Count Items in arr = [3 2 2 1 2]

---Two Dimensional Random Original Array----
[[47 25 28 61 23]
[78 15 75 77 98]
[31 58 94 99 15]]
Unique Items in arr2 = [15 23 25 28 31 47 58 61 75 77 78 94 98 99]
Count Items in arr2 = [2 1 1 1 1 1 1 1 1 1 1 1 1 1]

----Three Dimensional Random Original Array----
[[[17 16 18 20 18 24 20 22]
[24 22 17 17 19 18 18 21]
[15 19 19 18 16 24 19 21]]

[[24 16 16 24 24 16 19 19]
[17 15 17 15 15 17 23 20]
[22 15 24 16 21 22 24 22]]]
Unique Items in arr3 = [15 16 17 18 19 20 21 22 23 24]
Count Items in arr3 = [5 6 6 5 6 3 3 5 1 8]

Numpy Array Transpose

In Python, we have T and transpose function to transpose a matrix or an array. Transpose means rows converted to columns, and columns converted to rows.

import numpy as np
 
a = np.array([[26, 48, 91, 57, 120], [33, 95, 68, 109, 155],
             [111, 194, 7, 22, 124], [ 82, 119, 18, 156, 81],
             [ 38, 10, 151, 24, 14]])
 
b = np.array([[12, 11, 0, 9, 7], [10, 4, 11, 6, 9],
             [ 9, 2, 10, 9, 11], [ 5, 14, 0, 11, 8]])
 
print('Original Array')
print(a)
print('\nTransposed Array')
print(a.T)
 
print('\nOriginal Array')
print(b)
print('\nTransposed Array')
print(np.transpose(b))

Numpy Array transpose output

Original Array
[[ 26 48 91 57 120]
[ 33 95 68 109 155]
[111 194 7 22 124]
[ 82 119 18 156 81]
[ 38 10 151 24 14]]

Transposed Array
[[ 26 33 111 82 38]
[ 48 95 194 119 10]
[ 91 68 7 18 151]
[ 57 109 22 156 24]
[120 155 124 81 14]]

Original Array
[[12 11 0 9 7]
[10 4 11 6 9]
[ 9 2 10 9 11]
[ 5 14 0 11 8]]

Transposed Array
[[12 10 9 5]
[11 4 2 14]
[ 0 11 10 0]
[ 9 6 9 11]
[ 7 9 11 8]]

Python Array Functions

Python NumPy has many built-in functions. We already explained all these functions with examples on regular Python Tutorial.

Python Numpy Array functions and operatorsList of Numpy Functions and Operators
Arithmetic Operators+, -, *, /
Arithmetic Functionsadd, subtract, multiply, divide, mod, remainder
Aggregate Functions sum, average, prod, min, max, maximum, minimum, mean, median, var, std, cumsum, cumprod, percentile, argmin, argmax, corrcoef
Bitwise Operators&, |, ~, ^, left_shift, right_shift
Bitwise Functionsbitwise_and, bitwise_or, bitwise_not, bitwise_xor
Comparison Operators<, <=, ==, <, >=, !=
Comparison Functionsequal, less, less_equal, greater, greater_equal, not_equal
Logical Operatorsand, or, not
Logical Functionslogical_and, logical_or, logical_not, logical_xor
Exponentialexp, exp2, expm1, log, log2, log10, log1p
Mathematicalabs, ceil, floor, mod, modf, round, sinc, sign, trunc, square, reciprocal, power, sqrt, cbrt
Trigonometricsin, cos, tan, acsin, arccos, atctan, arctan2, radians, degrees, hypot, deg2rad, rad2deg, unwrap
Hyperbolicsinh, acsinh, cosh, arccosh, tanh, atctanh
Predicatesisfinite, isinf, isnan, signbit