NumPy

Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python. Besides its obvious scientific uses, Numpy can also be used as an efficient multi-dimensional container of generic data.

Arrays in Numpy: NumPy’s main object is the homogeneous multidimensional array.

  • It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers.

  • In NumPy dimensions are called axes. The number of axes is rank.

  • NumPy’s array class is called ndarray. It is also known by the alias array.

[[ 1, 2, 3],

[ 4, 2, 5]]

Here, rank = 2 (as it is 2-dimensional or it has 2 axes) first dimension(axis) length = 2, second dimension has length = 3 overall shape can be expressed as: (2, 3)

Example 1:

# Python program to demonstrate  
# basic array characteristics 
import numpy as np 
  
# Creating array object 
arr = np.array( [[ 1, 2, 3], 
                 [ 4, 2, 5]] ) 
  
# Printing type of arr object 
print("Array is of type: ", type(arr)) 
  
# Printing array dimensions (axes) 
print("No. of dimensions: ", arr.ndim) 
  
# Printing shape of array 
print("Shape of array: ", arr.shape) 
  
# Printing size (total number of elements) of array 
print("Size of array: ", arr.size) 
  
# Printing type of elements in array 
print("Array stores elements of type: ", arr.dtype) 

Array is of type: <class 'numpy.ndarray'>

No. of dimensions: 2

Shape of array: (2, 3)

Size of array: 6

Array stores elements of type: int32

Example 2:

# Python program to demonstrate 
# array creation techniques 
import numpy as np 
  
# Creating array from list with type float 
a = np.array([[1, 2, 4], [5, 8, 7]], dtype = 'float') 
print ("Array created using passed list:\n", a) 

Array created using passed list:

[[1. 2. 4.]

[5. 8. 7.]]

# Creating array from tuple 
b = np.array((1 , 3, 2)) 
print ("\nArray created using passed tuple:\n", b) 
  
# Creating a 3X4 array with all zeros 
c = np.zeros((3, 4)) 
print ("\nAn array initialized with all zeros:\n", c) 

Array created using passed tuple:

[1 3 2]

An array initialized with all zeros:

[[0. 0. 0. 0.]

[0. 0. 0. 0.]

[0. 0. 0. 0.]]

# Create a constant value array of complex type 
d = np.full((3, 3), 6, dtype = 'complex') 
print ("\nAn array initialized with all 6s." 
            "Array type is complex:\n", d) 
  
# Create an array with random values 
e = np.random.random((2, 2)) 
print ("\nA random array:\n", e) 

An array initialized with all 6s.Array type is complex:

[[6.+0.j 6.+0.j 6.+0.j]

[6.+0.j 6.+0.j 6.+0.j]

[6.+0.j 6.+0.j 6.+0.j]

A random array:

[[0.48429795 0.62234042]

[0.2816561 0.63487782]]

 # Create a sequence of integers  
# from 0 to 30 with steps of 5 
f = np.arange(0, 30, 5) 
print ("\nA sequential array with steps of 5:\n", f) 
  
# Create a sequence of 10 values in range 0 to 5 
g = np.linspace(0, 5, 10) 
print ("\nA sequential array with 10 values between"
                                        "0 and 5:\n", g) 

A sequential array with steps of 5:

[ 0 5 10 15 20 25]

A sequential array with 10 values between 0 and 5:

[0. 0.55555556 1.11111111 1.66666667 2.22222222 2.77777778 3.33333333 3.88888889 4.44444444 5. ]

# Reshaping 3X4 array to 2X2X3 array 
arr = np.array([[1, 2, 3, 4], 
                [5, 2, 4, 2], 
                [1, 2, 0, 1]]) 
  
newarr = arr.reshape(2, 2, 3) 
  
print ("\nOriginal array:\n", arr) 
print ("Reshaped array:\n", newarr) 
  
# Flatten array 
arr = np.array([[1, 2, 3], [4, 5, 6]]) 
flarr = arr.flatten() 
  
print ("\nOriginal array:\n", arr) 
print ("Fattened array:\n", flarr)

Original array:

[[1 2 3 4]

[5 2 4 2]

[1 2 0 1]]

Reshaped array:

[[[1 2 3]

[4 5 2]]

[[4 2 1]

[2 0 1]]]

Original array:

[[1 2 3]

[4 5 6]]

Fattened array:

[1 2 3 4 5 6]

Example 3:

# Python program for
# Creation of Arrays
import numpy as np
 
# Creating a rank 1 Array
arr = np.array([1, 2, 3])
print("Array with Rank 1: \n",arr)
 
# Creating a rank 2 Array
arr = np.array([[1, 2, 3],
                [4, 5, 6]])
print("Array with Rank 2: \n", arr)
 
# Creating an array from tuple
arr = np.array((1, 3, 2))
print("\nArray created using "
      "passed tuple:\n", arr)

OUTPUT:

Array with Rank 1:

[1 2 3]

Array with Rank 2:

[[1 2 3]

[4 5 6]]

Array created using passed tuple:

[1 3 2]

Accessing the array Index:

Example 4:

# Python program to demonstrate
# indexing in numpy array
import numpy as np
 
# Initial Array
arr = np.array([[-1, 2, 0, 4],
                [4, -0.5, 6, 0],
                [2.6, 0, 7, 8],
                [3, -7, 4, 2.0]])
print("Initial Array: ")
print(arr)
 
# Printing a range of Array
# with the use of slicing method
sliced_arr = arr[0:3:2, ::2]
print ("Array with first 2 rows and"
    " alternate columns(0 and 2):\n", sliced_arr)
 
# Printing elements at
# specific Indices
Index_arr = arr[[1, 1, 0, 3], 
                [3, 2, 1, 0]]
print ("\nElements at indices (1, 3), "
    "(1, 2), (0, 1), (3, 0):\n", Index_arr)

OUTPUT:

Initial Array:

[[-1. 2. 0. 4. ]

[ 4. -0.5 6. 0. ]

[ 2.6 0. 7. 8. ]

[ 3. -7. 4. 2. ]]

Array with first 2 rows and alternate columns(0 and 2):

[[-1. 0.]

[ 2.6. 7.]]

Elements at indices (1, 3), (1, 2), (0, 1), (3, 0):

[ 0. 6. 2. 3.]

Basic Array Operations:

Example 5:

# Python program to demonstrate
# basic operations on single array
import numpy as np
 
# Defining Array 1
a = np.array([[1, 2],
              [3, 4]])
 
# Defining Array 2
b = np.array([[4, 3],
              [2, 1]])
               
# Adding 1 to every element
print ("Adding 1 to every element:", a + 1)
 
# Subtracting 2 from each element
print ("\nSubtracting 2 from each element:", b - 2)
 
# sum of array elements
# Performing Unary operations
print ("\nSum of all array "
       "elements: ", a.sum())
 
# Adding two arrays
# Performing Binary operations
print ("\nArray sum:\n", a + b)

OUTPUT:

Adding 1 to every element:

[[2 3]

[4 5]]

Subtracting 2 from each element:

[[ 2 1]

[ 0 -1]]

Sum of all array elements: 10

Array sum:

[[5 5]

[5 5]]

Indexing using index arrays:

Example 6:

# Python program to demonstrate  
# the use of index arrays. 
import numpy as np 
  
# Create a sequence of integers from 10 to 1 with a step of -2 
a = np.arange(10, 1, -2)  
print("\n A sequential array with a negative step: \n",a) 
  
# Indexes are specified inside the np.array method. 
newarr = a[np.array([3, 1, 2 ])] 
print("\n Elements at these indices are:\n",newarr) 

OUTPUT:

A sequential array with a negative step: [10 8 6 4 2]

Elements at these indices are: [4 8 6]

Types of Indexing:

1. Basic Slicing and indexing:

Example 7:

# Python program for basic slicing. 
import numpy as np 
  
# Arrange elements from 0 to 19 
a = np.arange(20) 
print("\n Array is:\n ",a) 
  
# a[start:stop:step] 
print("\n a[-8:17:1]  = ",a[-8:17:1])  
  
# The : operator means all elements till the end. 
print("\n a[10:]  = ",a[10:])

OUTPUT:

Array is:

[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]

a[-8:17:1] = [12 13 14 15 16]

a[10:] = [10 11 12 13 14 15 16 17 18 19]

2. Advanced indexing:

Advanced indexing is triggered when obj is :

  1. an array of type integer or Boolean

  2. or a tuple with at least one sequence object

  3. is a non tuple sequence object

Example 8:

# Python program showing advanced indexing 
import numpy as np 
  
a = np.array([[1 ,2 ],[3 ,4 ],[5 ,6 ]]) 
print(a[[0 ,1 ,2 ],[0 ,0 ,1]])

OUTPUT:

[1 3 6]

Example 9:

# You may wish to select numbers greater than 50 
import numpy as np 
  
a = np.array([10, 40, 80, 50, 100]) 
print(a[a>50])

OUTPUT:

[80 100]

Example 10:

# You may wish to square the multiples of 40  
import numpy as np 
  
a = np.array([10, 40, 80, 50, 100]) 
print(a[a%40==0]**2) 

OUTPUT:

[1600 6400]

numpy.sum() in Python

numpy.sum(axis) : This function returns the sum of array elements over the specified axis.

axis : axis along which we want to calculate the sum value. Otherwise, it will consider arr to be flattened(works on all the axis). axis = 0 means along the column and axis = 1 means working along the row.s function returns the sum of array elements over the specified axis.

Example 11:

# You may wish to select those elements whose 
# sum of row is a multiple of 10. 
import numpy as np 
  
b = np.array([[5, 5],[4, 5],[16, 4]]) 
sumrow = b.sum(1) 
print(sumrow)
print(b[sumrow%10==0]) 

OUTPUT:

[10 9 20]

[[ 5 5]

[16 4]]

Example 12:

# Python program to demonstrate 
# unary operators in numpy 
import numpy as np 
  
arr = np.array([[1, 5, 6], 
                [4, 7, 2], 
                [3, 1, 9]]) 
  
# maximum element of array 
print ("Largest element is:", arr.max()) 
print ("Row-wise maximum elements:", 
                    arr.max(axis = 1)) 
  
# minimum element of array 
print ("Column-wise minimum elements:", 
                        arr.min(axis = 0)) 
  
# sum of array elements 
print ("Sum of all array elements:", 
                            arr.sum()) 
  
# cumulative sum along each row 
print ("Cumulative sum along each row:\n", 
                        arr.cumsum(axis = 1)) 

Largest element is: 9

Row-wise maximum elements: [6 7 9]

Column-wise minimum elements: [1 1 2]

Sum of all array elements: 38

Cumulative sum along each row:

[[ 1 6 12]

[ 4 11 13]

[ 3 4 13]]

Example 13:

# Python program to demonstrate 
# binary operators in Numpy 
import numpy as np 
  
a = np.array([[1, 2], 
            [3, 40]]) 
b = np.array([[4, 3], 
            [2, 1]]) 
  
# add arrays 
print ("Array sum:\n", a + b) 
  
# multiply arrays (elementwise multiplication) 
print ("Array multiplication:\n", a*b) 
  
# matrix multiplication 
print ("Matrix multiplication:\n", a.dot(b)) 

Array sum:

[[5 5]

[5 5]]

Array multiplication:

[[4 6]

[6 4]]

Matrix multiplication:

[[ 8 5]

[20 13]]

Last updated