NumPy Cheat Sheet

NumPy Cheat Sheet

NumPy Cheat Sheet will guide you to work on NumPy with basics and advanced topics. Cheat Sheet for students, engineers, and professionals.

Introduction

NumPy is a Python library for numeric and scientific computing. It stands for numerical python and consists of multi-dimensional array objects.

Installation

To install NumPy, use the PIP package manager. Install Python and PIP, and then use PIP to install the NumPy Python library:

pip install numpy

Create NumPy Arrays

To create Numpy arrays, use numpy.arrays() method in Python:

  • Create a Numpy array by passing a tuple:
    n = np.array((1, 2, 3))
    print(n)
  • Create a Numpy array by passing a list:
    n = np.array([1, 2, 3])
    print(n)

Dimensions of NumPy Arrays

Dimensions of an array in NumPy are also called the Rank of an Array. Check how many dimensions an array has used with the numpy.ndarray.ndim:

  • Create a Zero-dimensional NumPy array:
    import numpy as np
     
    n = np.array(25)
    print("Dimensions = ",n.ndim) # Dimensions = 0
  • Create a One-dimensional NumPy array:
    import numpy as np 
    
    n = np.array([10, 20, 30])
    print("Dimensions = ",n.ndim) # Dimensions = 1
  • Create a Two-dimensional NumPy array:
    import numpy as np
    
    n = np.array([[1,3,5],[4,8,12]])
    print("Dimensions = ",n.ndim) # Dimensions = 2

Initialize NumPy Arrays

To Initialize NumPy arrays, use the numpy.zeros() method. Let us see how to initialize numpy arrays with zeros:

import numpy as np
 
n = np.zeros([2, 3])
print(n)

Output

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

Array Indexing

Array indexing is accessing array elements. In Numpy, access an array element using the index number. The 0th index is element 1 and the flow goes on as shown below:

  •   index 0 – element 1
  •   index 1 – element 2
  •   index 2 – element 3
  •   index 3 – element 4

Let us see some examples:

  • Access the 1st element (index 0) from a One-Dimensional array:
    import numpy as np
     
    n = np.array([10, 20, 30, 40, 50])
    print(n[0]) # 10
  • Accessing 1st dimension elements from a 2D array:
    import numpy as np
     
    n = np.array([[1,3,5],[4,8,12]])
     
    print(n[0,1]) # 3
  • Access the last element from a 1D array with negative indexing:
    import numpy as np
     
    n = np.array([5, 10, 15])
    print(n[-1]) # 15

Array Slicing

Slicing the array in a range from start to end is what we call Array Slicing. The following is the syntax to slice NumPy arrays. Here, start is the beginning index (include), and the end is the last index (excluded):

arr[start:end}

Let us see some examples:

  • Slicing from index 1 to 3 (3 is excluded):
    import numpy as np
     
    n = np.array([20, 25, 30, 35, 40, 45, 50])
    print(n[1:3]) # [25 30]
  • Slicing from index 5 to last:
    import numpy as np
     
    n = np.array([20, 25, 30, 35, 40, 45, 50])
    print(n[:5]) # [20 25 30 35 40]

NumPy Datatypes

Python Numpy supports the following data types:

  • b – boolean
  • u – unsigned integer
  • f – float
  • c – complex float
  • m – timedelta
  • M – datetime
  • O – object
  • S – string
  • U – unicode string

Let us see some examples:

  • Get the datatype of a Numpy array with strings:
    import numpy as np
     
    n = np.array(["amit", "rohit", "ashwin", "jadeja", "virat"])
    print(n.dtype) # <U6
  • Convert string to integer:
    import numpy as np
     
    n = np.array(['10', '20', '30', '40', '50'])
    print(n)
    print(n.dtype)
     
    n2 = n.astype('i')
    print(n2)
    print(n2.dtype)

    Output

    ['10' '20' '30' '40' '50']
    <U2
    [10 20 30 40 50]
    int32

NumPy Array Shape

In Python Numpy, the number of elements in each dimension of an array is called the shape. To get the shape of a Numpy array, use the numpy.shape attribute in Python:

  • Check the shape of a Zero-Dimensional NumPy array:
    import numpy as np
     
    n = np.array(10)
    print(n.shape) # ()
  • Check the shape of a One-Dimensional NumPy array:
    import numpy as np
     
    n = np.array([10, 20, 30])
    print(n.shape) # (3,)

Reshape a NumPy Array

To reshape the number of dimensions, use the numpy.reshape() method in Python. Reshape allows you to edit the number of elements in a dimension. Let us reshape dimensions from 1D to 2D:

import numpy as np
 
# Create a Numpy array
n = np.array([5, 10, 15, 20, 25, 30])
print("One-Dimensional Array = ",n)
 
# Reshape the array
resarr = n.reshape(2, 3)
 
print("Reshaped array (Two-Dimensional) = \n",resarr)

Output

One-Dimensional Array =  [ 5 10 15 20 25 30]
Reshaped array (Two-Dimensional) = 
 [[ 5 10 15]
 [20 25 30]]

Iterate Numpy Arrays

Iteration displays each element of an array. We will see how to iterate through Numpy arrays using loops. Let us iterate a One-Dimensional Numpy array:

import numpy as np
 
# Create a Numpy 1D array
n = np.array([5, 10, 15, 20, 25, 30])
print("One-Dimensional Array = ",n)
print("Type = ",type(n))
print("DataType = ",n.dtype)
 
print("\nIterating...")
for a in n:
  print(a)

Output

One-Dimensional Array =  [ 5 10 15 20 25 30]
Type =  <class 'numpy.ndarray'>
DataType =  int32
 
Iterating...
5
10
15
20
25
30

Joining NumPy Arrays

We can join two or more arrays in a single new array:

import numpy as np
 
# Create two arrays
n1 = np.array([5, 10, 15, 20])
n2 = np.array([25, 30, 35, 40])
 
# Joining arrays
resarr = np.concatenate((n1, n2))
print("\nAfter Joining = ", resarr)

Output

After Joining = [ 5 10 15 20 25 30 35 40]

Join arrays in Numpy using the stack methods, such as:

  • stack(): Join arrays
  • hstack(): Stack along rows
  • vstack(): Stack along columns
  • dstack(): Stack along depth
  • column_stack(): Stack according to columns

Split NumPy Array

To split an array, use the array_split() method. Following is the syntax:

array_split(arr_name, split_num)

Here, arr_name is the name of the array, split_num is the count of splits.

Let us see how to split a 1d array:

import numpy as np
 
# Create a Numpy array
n = np.array([10, 20, 30, 40, 50, 60])
 
# splitting array into 2
resarr = np.array_split(n, 2)
 
print("\nArray after splitting i.e. returns 2 arrays");
for a in resarr:
    print(a)

Output

Array after splitting i.e. returns 2 arrays
[10 20 30]
[40 50 60]

Search an array for a value

In a Numpy array, we can search for a specific value using the numpy.where() method. This method returns the index where the specific element is found. Let us see an example:

import numpy as np
 
# Create a Numpy Array
n = np.array([10, 20, 30, 40, 50, 30])
 
# Searching a specific value 30
res = np.where(n == 30)
 
print("\nElement 30 found at following indexes:")
print(res)

Output

Element 30 found at following indexes:
(array([2, 5], dtype=int64),)

Sort Arrays

The numpy.sort() function is used in Numpy to sort arrays in a sequence. This sequence can be ascending or descending. Let us see how to sort arrays:

import numpy as np
 
# Create a 1D integer array
n = np.array([50, 25, 35, 15, 55, 75, 65, 60, 30, 45])
 
# Sort the array using the sort() method
print("\nSorted array = ", np.sort(n))

Output

Sorted array =  [15 25 30 35 45 50 55 60 65 75]

Axes in Arrays

In Numpy arrays, the axis is the direction along the rows and columns. A two-dimensional numpy array has the following two corresponding axes:

vertical axis (axis 0)
horizontal axis (axis 1)

Let us see an example to get the minimum value with axes:

import numpy as np
 
# Create a numpy 3x3 array
n = np.array([[2, 5, 7, 9, 6], [15, 25, 35, 45, 55], [100, 200, 300, 400, 500]])
 
print("\nMinimum value = ", n.min())
print("\nMinimum value with axis 0 (vertical axes) = ", n.min(axis=0))
print("\nMinimum value with axis 1 (horizontal axes) = ", n.min(axis=1))

Output

Minimum value =  2
Minimum value with axis 0 (vertical axes) =  [2 5 7 9 6]
Minimum value with axis 1 (horizontal axes) =  [  2  15 100]

Intersection of NumPy Arrays

If you want to get the intersection of two arrays, use the intersect1d() method in Numpy. Intersection means finding common elements between two arrays.  Let us see an example:

import numpy as np
 
# Create two arrays
n1 = np.array([5, 10, 15, 20])
n2 = np.array([5, 15, 30, 40])
 
print("Iterating array1...")
for a in n1:
    print(a)
 
print("\nIterating array2...")
for a in n2:
    print(a)
 
# Find intersection using the intersect1d() method
resarr = np.intersect1d(n1, n2)
print("\nIntersection = \n", resarr)

Output

Iterating array1...
5
10
15
20
 
Iterating array2...
5
15
30
40
 
Intersection = 
 [ 5 15]

Difference between NumPy Arrays

To find the difference between two arrays, use the numpy.setdiff1d() method. This means if we are subtracting two arrays, then setdiff1d() will subtract the common elements from the 1st array and display the rest of the elements of the 1st array. Let us see an example:

import numpy as np
 
# Create two arrays
n1 = np.array([5, 10, 15, 20, 25, 30, 35, 40, 45, 50])
n2 = np.array([30, 35, 50, 55, 60, 65, 75, 85, 95, 100])
 
# n1 - n2
diffarr = np.setdiff1d(n1, n2)
print("\nDifference = \n", diffarr)

Output

Difference = 
 [ 5 10 15 20 25 40 45]

Arithmetic operations between NumPy Arrays

Perform arithmetic operations on Numpy arrays:

  • Add Numpy Arrays: Use the sum() method to add arrays:
    import numpy as np
     
    # Create arrays
    n1 = np.array([15, 20, 25, 30])
    n2 = np.array([65, 75, 85, 95])
     
    # Add the arrays elements
    resarr = np.sum([n1, n2])
    print("Sum = ", resarr) # Sum = 410
  • Subtract Numpy Arrays: Use the subtract() method to subtract one array from another:
    import numpy as np
     
    # Create two arrays
    n1 = np.array([15, 20, 25, 30])
    n2 = np.array([65, 75, 85, 95])
     
    # Subtract Numpy arrays
    resarr = np.subtract(n1, n2)
    print("Subtraction result = ", resarr) # [-50 -55 -60 65]
  • Multiply Numpy Arrays: Use the multiply() method to multiply elements of one array to another:
    import numpy as np
     
    # Create Numpy arrays
    n1 = np.array([15, 20, 25, 30])
    n2 = np.array([65, 75, 85, 95])
     
    # Multiply Numpy arrays
    resarr = np.multiply(n1, n2)
    print("Multiplication result = ", resarr) # [975 1500 2125 2850]
  • Divide Numpy Arrays: The divide() method divides elements of one array with elements of another:
    import numpy as np
     
    # Create two Numpy arrays
    n1 = np.array([15, 20, 25, 30])
    n2 = np.array([65, 75, 85, 95])
     
    # Divide arrays
    resarr = np.divide(n2, n1)
    print("Division Result = ", resarr) # [4.33333333 3.75       3.4        3.16666667]
    

Scalar Operations on NumPy Arrays

Scalar operations on Numpy arrays include performing:

  • Addition Operation on Numpy Arrays: The Addition Operation adds a value to each element of a NumPy array:
    n = np.array([15, 20, 25, 30])
     
    # performing addition on each element
    n = n + 10;
  • Subtraction Operation on Numpy Arrays: The Subtraction operation is subtracting a value from each element of a NumPy array:
    n = np.array([15, 20, 25, 30])
     
    # performing subtraction on each element
    n = n - 10;
  • Multiplication Operation on Numpy Arrays: The Multiplication operation is multiplying a value to each element of a NumPy array:
    n = np.array([15, 20, 25, 30]) 
    
    # performing multpilication on each element
    n = n * 10;
  • Division Operation on Numpy Arrays: The Division operation is to divide a value from each element of a NumPy array:
    n = np.array([15, 20, 25, 30])
    
    # performing division on each element
    n = n / 5;

Statistical Operations on NumPy Arrays

We can perform statistical operations, like mean, median, and standard deviation on NumPy arrays:

  • Mean: Mean is the average of the given values. Here, we will find the mean of the array elements using the mean() method:
    import numpy as np
     
    # Create two arrays
    n = np.array([15, 20, 25, 30])
     
    # mean
    resmean = np.mean(n);
     
    print("\nMean = ", resmean) # 22.5
  • Median: Median is the middle value of the given values. Here, we will find the median of the array elements using the median() method:
    import numpy as np
     
    # Create two arrays
    n = np.array([15, 20, 25, 30])
     
    # median
    resmedian = np.median(n);
     
    print("\nMedian = ", resmedian) # 22.5
  • Standard Deviation: Standard Deviation is a measure of the amount of variation or dispersion of the given values. Here, we will find the standard deviation of the array elements using the std() method:
    import numpy as np
     
    # Create two arrays
    n = np.array([15, 20, 25, 30])
     
    # standard deviation
    resmean = np.mean(n);
     
    print("\nStandard Deviation = ", resmean) # 5.5901699437494745

What’s next?

After completing NumPy, follow the below tutorials and learn Python Libraries:

If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


Numpy LCM and HCF
NumPy Online Quiz
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment