Python NumPy Array

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, or an array. Like any other programming language, 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 one to get shape and dtype.
  • ones: Creates an array of 1’s of a given shape and data type.
  • ones_like: It accepts another to read its shape and data type.
  • empty, empty_like: These functions create an empty one 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 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)
[1 2 3 4 5 6 7 8 9]

Create Python Array from List

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

We also create create an ndarray of mixed items in Python.

import numpy as np

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

b = [2.5, 3.5, 7, 4.5, 8]
arr2 = np.array(b)
print(arr2)
[1 2 3 4 5]

[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 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 or nested list.

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.

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      = ', arr)
print('Add 5      = ', arr + 5)
print('Multiply arr with 2 = ', arr * 2)

Vector operations on Python numpy ndarray output.

Original = [1 2 3 4 5]
Add 5 = [ 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.

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 ndarray 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) returns 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. Add print function.

[0, 1, 2, 3, 4]

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

[ 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) returns the numbers from 0 to 1 in five equal steps.

import numpy as np

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

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

print(np.linspace(0, 1, 7))

print(np.linspace(10, 100, 20))

Python Numpy linespace function to create ndarray output

[0.   0.25 0.5  0.75 1.  ]
[ 0.   2.5  5.   7.5 10. ]
[0.         0.16666667 0.33333333 0.5        0.66666667 0.83333333
 1.        ]
[ 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. For example,

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

print(np.zeros(3))
print(np.zeros((2, 2)))

print(np.zeros((2, 3)))
print(np.zeros((4, 7)))
print(np.zeros((3, 2, 7)))
[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. 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 it. For example,

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

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

Python Numpy ndarray of ones 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. 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. 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 article

import numpy as np

print(np.random.random(5))
print(np.random.random((4, 4)))
print(np.random.random((2, 3, 4)))
[0.17481245, 0.20246847, 0.95714739, 0.93449316, 0.00816149]

[[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]]

[[[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, 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 empty ndarray output

[3., 2., 1.]

[[4.33404091e-311, 1.97626258e-323, 1.20871698e-315],
       [2.14187885e-296, 8.58539581e-210, 6.25613152e-309]]

[[-0.00000000e+000,  4.33404091e-311,  1.97626258e-323,
                     nan],
       [ 1.20871698e-315,  2.14187885e-296, -8.58539581e-210,
         6.25613152e-309]]

[[[-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 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)
[4, 4, 4, 4, 4]

[[9, 9, 9, 9],
       [9, 9, 9, 9],
       [9, 9, 9, 9]]

[[8, 8, 8, 8],
       [8, 8, 8, 8],
       [8, 8, 8, 8],
       [8, 8, 8, 8]]

[[[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

print(np.eye(2))
print(np.eye(3))
print(np.eye(5))
[[1., 0.],
       [0., 1.]]

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

[[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 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])
>>> 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 items using the index position. The index position always starts at 0 and ends at n-1, where n is the size, row size, or column size, or dimension. Access the items from one-dimensional.

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 elements, you can alter numpy array items using the index position. It is an example to access the items from a one-dimensional.

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

[10, 20, 30, 40, 50])

[150,  20,  30,  40,  50]

[150,  20,  30, 111,  50]

[[  10,   50,  100],
       [ 250,  500, 1000]]

[[  99,   50,  100],
       [ 250,  500, 1000]]

[[  99,   50,  100],
       [ 250,  222, 1000]]

[[ 99,  50, 100],
       [250, 222, 444]]

Python Numpy array Slicing

First, we declare a single or one-dimensional array and slice that one. Python slicing accepts an index position of start and endpoint. 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 ndarray 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.

Python One dimensional 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]
[ 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 and slicing the same using index values.

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]])

print(arr2)
 
print(arr2[:2, :2])
print(arr2[:3, :4])

print(arr2[:3, ])
print(arr2[:3])
print(arr2[:4])
print(arr2[:,:4])

Python Two Dimensional numpy ndarray slicing output

[[ 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]]
[[26 48]
 [33 95]]
[[ 26  48  91  57]
 [ 33  95  68 109]
 [111 194   7  22]]
[[ 26  48  91  57 120]
 [ 33  95  68 109 155]
 [111 194   7  22 124]]
[[ 26  48  91  57 120]
 [ 33  95  68 109 155]
 [111 194   7  22 124]]
[[ 26  48  91  57 120]
 [ 33  95  68 109 155]
 [111 194   7  22 124]
 [ 82 119  18 156  81]]
[[ 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.

>>> 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]])
 
print(arr1[::-1])
# Reverse the row position only
print(arr2[::-1,])
 
# Reverse both the row and column position
print(arr2[::-1, ::-1])
[250, 150, 100,  50,  10]

[[ 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]]

[[ 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

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

Creating an array using 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(arr1)
print(Bool index : ", x)
print(arr1[x])
 
y = arr1 < 40
print("\nBool index : ", y)
print(arr1[y])
 
arr2 = np.array(np.random.randint(1, 10, size = (3, 8)))
z = arr2 > 4 
print("\n-----Arr2------\n", arr2)
print("------Bool index------\n", z)
print("------Arr2 of Z------\n", arr2[z])
[10 20 50 90 5 40 60 30 25]
Bool index : [False False True True False False True False False]
[50 90 60]

Bool index : [ True True False False True False False True True]
[10 20 5 30 25]

----- Arr2 ------
[[3 1 5 9 9 8 9 9]
[7 8 8 6 6 7 5 3]
[8 8 2 6 8 2 2 8]]
------ 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]]
------ Arr2 of Z ------
[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(arr1)

arr1[2] = np.nan
arr1[4] = np.inf
print(arr1)

# Replace inf and nan With 11.56
x = np.isinf(arr1) | np.isnan(arr1)
arr1[x] = 11.56
print(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("\n-----------\n")
print( arr2)

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

Output of replacing NaN and Infinity values of Python ndarray

[10. 20. 50. 90.  5. 40. 60. 30. 25.]
[10. 20. nan 90. inf 40. 60. 30. 25.]
[10.   20.   11.56 90.   11.56 40.   60.   30.   25.  ]

-----------
 [[ 9.  7. nan  8. inf]
 [nan  3.  7. inf  5.]
 [ 8. inf  4. nan  1.]]
------------
 [[ 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.

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

print(arr + 4)
print(arr - 8)
print(arr * 3)

two = np.array([[1, 2, 3, 4, 5],[12, 15, 61, 11, 19]])
print(two)
print(two + 10)
print(two - 3)
print(two * 2)

three = np.array([[1, 2, 3], [10, 20, 30], [6, 7, 8]])
print(three + 2)
print(three - 5)
print(three * 5)
[10 15 25 35 45 55 65]
[14 19 29 39 49 59 69]
[ 2  7 17 27 37 47 57]
[ 30  45  75 105 135 165 195]
[[ 1  2  3  4  5]
 [12 15 61 11 19]]
[[11 12 13 14 15]
 [22 25 71 21 29]]
[[-2 -1  0  1  2]
 [ 9 12 58  8 16]]
[[  2   4   6   8  10]
 [ 24  30 122  22  38]]
[[ 3  4  5]
 [12 22 32]
 [ 8  9 10]]
[[-4 -3 -2]
 [ 5 15 25]
 [ 1  2  3]]
[[  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 dimension. If it is a one-dimensional, then 1, two-dimensional = 2, etc.
  • size: It displays or returns the number of elements or items.
  • flags: Information about the memory layout.
  • itemsize: Length in bytes.
  • nbytes: Total number of bytes consumed it.

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('Dimension = ', a.ndim)
print('No of Elements = ', a.size)
print('Memory Layout = ', a.flags)
print('Length in Bytes = ', a.itemsize)
print('Total bytes consumed = ', a.nbytes)
 
print('\nDimension = ', b.ndim)
print('No of Elements = ', b.size)
print('Memory Layout = ', b.flags)
print('Length in Bytes = ', b.itemsize)
print('Total bytes consumed = ', b.nbytes)
Dimension =  1
No of Elements =  5
Memory Layout =    C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

Length in Bytes =  8
Total bytes consumed =  40

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

Length in Bytes =  8
Total bytes consumed =  200

Python ndarray shape

Python ndarray shape object is useful to display the array shape precisely, and 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 the one that we create. However, the Python array function also allows you to specify the data type explicitly using dtype. Using this dtype object, either you can see the data type assigned to it implicitly or can assign your own data type explicitly.

In this example, we created a 1d, two-dimensional, and three-dimensional. Next, we are using this 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("Arr 1.      : ", arr1)
print("Arr 1 Shape : ", arr1.shape)
 
print("Arr 2       : \n", arr2)
print("Arr 2 Shape : ", arr2.shape)
 
print("Arr 3       : \n", arr3)
print("Arr 3 Shape : ", arr3.shape)

ndarray shape output

Arr 1.      :  [ 10  50 100 150 250]
Arr 1 Shape :  (5,)
Arr 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]]
Arr 2 Shape :  (5, 5)
Arr 3       : 
 [[12 11  0  9  7]
 [10  4 11  6  9]
 [ 9  2 10  9 11]
 [ 5 14  0 11  8]]
Arr 3 Shape :  (4, 5)

Python ndarray dtype

Generally, Python assigns a proper data type to an array that we create. However, the Python 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 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("Arr          : ", arr1)
print("Data Type : ", arr1.dtype)
 
arr2 = np.array([1, 3.10, 4.60, 5, 7.96])
 
print("\nArr         : ", arr2)
print("Data Type : ", arr2.dtype)
Arr           :  [10 20 30 40 50]
Data Type :  int64

Arr         :  [1.   3.1  4.6  5.   7.96]
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("Arr           : ", arr1)
print("Data Type : ", arr1.dtype)
 
arr2 = np.array(list1, dtype = 'float')
print("Arr2           : ", arr2)
print("Data Type : ", arr2.dtype)
 
arr3 = np.array(list1, dtype = 'float16')
print("Arr3           : ", arr3)
print("Data Type : ", arr3.dtype)
Arr           :  [10 20 30 40 50]
Data Type :  int64
Arr2           :  [10. 20. 30. 40. 50.]
Data Type :  float64
Arr3           :  [10. 20. 30. 40. 50.]
Data Type :  float16

A few more 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("Arr1           : ", arr1)
print("Arr1 Data Type : ", arr1.dtype)
 
arr2 = np.array(list1, dtype = 'bool')
print("Arr2           : ", arr2)
print("Arr2 Data Type : ", arr2.dtype)
 
arr3 = np.array([1, 10, 'e', 'o', 9, 'Hi', 7], dtype = 'object')
print("Arr3           : ", arr3)
print("Arr3 Data Type : ", arr3.dtype)

ndarray dtype properties output

Arr1           :  [b'1' b'20' b'0' b'40' b'0']
Arr1 Data Type :  |S2
Arr2           :  [ True  True False  True False]
Arr2 Data Type :  bool
Arr3           :  [1 10 'e' 'o' 9 'Hi' 7]
Arr3 Data Type :  object

Python ndarray reshape

The Python Numpy Array reshape function helps to reshape or change the size as per your requirement. Here, First, we are changing single dimensional to two-dimensional. 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("Arr            : ", arr1)
 
x = arr1.reshape(2, 4)
print("------New 2 * 4------\n", x)
 
y = arr1.reshape(4, 2)
print("------New 4 * 2------\n", y)
 
arr2 = np.array( np.random.randint(1, 9, size = (3, 4)))
print("-----Arr2------\n", arr2)
 
a = arr2.reshape(4, 3)
print("------New Arr2 4 * 3------\n", a)
 
b = arr2.reshape(2, 6)
print("------New Arr2 2 * 6------\n", b)
Arr            :  [10 20 30 40 50 60 70 80]
------New 2 * 4------
 [[10 20 30 40]
 [50 60 70 80]]
------New 4 * 2------
 [[10 20]
 [30 40]
 [50 60]
 [70 80]]
-----Arr2------
 [[6 2 5 5]
 [8 6 2 1]
 [4 3 1 8]]
------New Arr2 4 * 3------
 [[6 2 5]
 [5 8 6]
 [2 1 4]
 [3 1 8]]
------New Arr2 2 * 6------
 [[6 2 5 5 8 6]
 [2 1 4 3 1 8]]

Python Numpy flatten and ravel

Both Python Numpy Array flattens, and ravel functions flatten or converts any size to a single dimensional. Although both are the same, the ravel function holds the reference of an actual one. 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("-----Arr------\n", arr1)
 
x = arr1.flatten()
print("------flatten------\n", x)
 
y = arr1.ravel()
print("------ravel------\n", y)
 
arr2 = np.array(np.random.randint(10, 30, size = (2, 3, 4)))
print("-----2nd------\n", arr2)
 
a = arr2.flatten()
print("------flatten 2------\n", a)
 
b = arr2.ravel()
print("------ravel 2------\n", b)

flatten and ravel functions output

-----Arr------
 [[ 7 15  5 11 18  9]
 [17 19  6  6 19  5]
 [10  7  6  8 13  7]]
------flatten------
 [ 7 15  5 11 18  9 17 19  6  6 19  5 10  7  6  8 13  7]
------ravel------
 [ 7 15  5 11 18  9 17 19  6  6 19  5 10  7  6  8 13  7]
-----2nd------
 [[[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 2------
 [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 2------
 [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 Array module has a unique function used to find and return the unique values from a given 1D, 2D, and 3 or multi Dimensional.

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

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

----Three Dimensional Random Original ----
[[[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 = [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 Numpy array. For this, you have to use the 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 = ', arr)
 
uniq, cnt = np.unique(arr, return_counts = True)
print('Unique Items = ', uniq)
print('Count Items = ', cnt)
 
arr2 = np.random.randint(10, 100, size = (3, 5))
print('\n---Two Dimensional Random Original ----\n', arr2)
 
uniq2, cnt2 = np.unique(arr2, return_counts = True)
print('Unique Items = ', uniq2)
print('Count Items = ', cnt2)
 
arr3 = np.random.randint(15, 25, size = (2, 3, 8))
print('\n----Three Dimensional Random Original ----\n', arr3)
 
uniq3, cnt3 = np.unique(arr3, return_counts = True)
print('Unique Items = ', uniq3)
print('Count Items = ', cnt3)
Original = [0 1 1 0 2 4 2 3 4 0]
Unique Items = [0 1 2 3 4]
Count Items = [3 2 2 1 2]

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

----Three Dimensional Random Original ----
[[[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 = [15 16 17 18 19 20 21 22 23 24]
Count Items = [5 6 6 5 6 3 3 5 1 8]

Python 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')
print(a)
print('\nTransposed ')
print(a.T)
 
print('\nOriginal')
print(b)
print('\nTransposed')
print(np.transpose(b))
Original
[[ 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
[[ 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
[[12 11 0 9 7]
[10 4 11 6 9]
[ 9 2 10 9 11]
[ 5 14 0 11 8]]

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

Built-in Functions

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

Functions and operatorsList of 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
MathematicalThe list of mathematical functions are abs, 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