0% found this document useful (0 votes)
2 views33 pages

1 NumPy Cheat Sheet - Beginner To Advanced PDF

The NumPy Cheat Sheet provides a comprehensive overview of NumPy, a crucial library for numerical computing in Python, covering topics from basic array creation to advanced mathematical operations. It includes practical examples and commands for creating, manipulating, and inspecting arrays, as well as saving and loading data files. By utilizing this cheat sheet, users can enhance their understanding and application of NumPy for data analysis.

Uploaded by

G. One
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views33 pages

1 NumPy Cheat Sheet - Beginner To Advanced PDF

The NumPy Cheat Sheet provides a comprehensive overview of NumPy, a crucial library for numerical computing in Python, covering topics from basic array creation to advanced mathematical operations. It includes practical examples and commands for creating, manipulating, and inspecting arrays, as well as saving and loading data files. By utilizing this cheat sheet, users can enhance their understanding and application of NumPy for data analysis.

Uploaded by

G. One
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

NumPy Cheat Sheet: Beginner to Advanced (PDF)


Last Updated : 18 Mar, 2024

NumPy stands for Numerical Python. It is one of the most important


foundational packages for numerical computing & data analysis in Python.
Most computational packages providing scientific functionality use NumPy’s
array objects as the lingua franca for data exchange.

InCheat
HTML thisSheet
NumpyCSSCheat sheetJS for
Cheat Sheet CheatData
Sheet Analysis, we’ve
Bootstrap Cheat Sheetcovered
jQuery the
Cheatbasics
Sheet to
Angular C
advanced functions of Numpy including creating arrays, Inspecting
properties as well as file handling, Manipulation of arrays, Mathematics
Operations in Array and more with proper examples and output. By the end
of this Numpy cheat sheet, you will gain a fundamental comprehension of
NumPy and its application in Python for data analysis.

NumPy Cheat Sheet

What is NumPy?
NumPy was initially created by Travis Oliphant in 2005 as an open-source
project. NumPy is a powerful Python library that provides support for large,
multi-dimensional arrays and matrices, along with a wide collection of
mathematical functions to operate on these arrays. It is an essential tool for
scientific computing and data analysis in Python.

Numpy CheatSheat PDF Download (Free)

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 1/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

Table of Content:
Creating Arrays Commands
Initial Placeholders
Inspecting Properties
Saving and Loading File
Sorting Array
NumPy Array Manipulation
Combining and Splitting Commands
Indexing, Slicing and Subsetting
Copying and Viewing Array
NumPy Array Mathematics
Benefits of Using NumPy Cheat Sheet
Applications of NumPy
Feature of NumPy
NumPy Cheat Sheet – FAQs

NumPy Cheat Sheet 2023


1. Creating Arrays Commands
Arrays in NumPy are of fixed size and homogeneous in nature. They are
faster and more efficient because they are written in C language and are
stored in a continuous memory location which makes them easier to
manipulate. NumPy arrays provide N-dimensional array objects that are
used in linear algebra, Fourier Transformation, and random number
capabilities. These array objects are much faster and more efficient than the
Python Lists.

Creating One Dimensional Array

NumPy one-dimensional arrays are a type of linear array. We can create a


NumPy array from Python List, Tuple, and using fromiter() function.

Creating One Dimensional Array Example

From Python List np.array([1, 2, 3, 4, 5])

From Python Tuple np.array((1, 2, 3, 4, 5))

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 2/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

Creating One Dimensional Array Example

fromiter() function np.fromiter((a for a in range(8)), float)

Python3

# create a NumPy array from a list


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

# create a NumPy array from a tuple


tup = (5, 6, 7, 8)
print(np.array(tup))

# create a NumPy array using fromiter()


iterable = (a for a in range(8))
print(np.fromiter(iterable, float))

Output:

[1 2 3 4]
[5 6 7 8]
[0. 1. 2. 3. 4. 5. 6. 7.]

Creating Multi-Dimensional Array

Numpy multi-dimensional arrays are stored in a tabular form, i.e., in the form
of rows and columns.

Create Two Dimensional Example


Array

np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11,


Using Python Lists
12]])

Using
np.empty([4, 3], dtype=int)
empty()

Python3
https://www.geeksforgeeks.org/numpy-cheat-sheet/ 3/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

# create a NumPy array from a list


list_1 = [1, 2, 3, 4]
list_2 = [5, 6, 7, 8]
list_3 = [9, 10, 11, 12]
print(np.array([list_1, list_2, list_3]))

# create a NumPy array using numpy.empty()


print(np.empty([4, 3], dtype=int))

Output:

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

2. Initial Placeholders
Example 1: For 1-Dimensional NumPy Arrays

Initial placeholders for a Numpy 1-dimension array can be created by using


various Numpy functions.

Initial Placeholders for 1D Array Example

arange() np.arange(1, 10)

linespace() np.linspace(1, 10, 3)

zeros() np.zeros(5, dtype=int)

ones() np.ones(5, dtype=int)

random.rand() np.random.rand(5)

random.randint() np.random.randint(5, size=10)

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 4/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

Python3

# create a NumPy array using numpy.arange()


print(np.arange(1, 10))

# create a NumPy array using numpy.linspace()


print(np.linspace(1, 10, 3))

# create a NumPy array using numpy.zeros()


print(np.zeros(5, dtype=int))

# create a NumPy array using numpy.ones()


print(np.ones(5, dtype=int))

# create a NumPy array using numpy.random.rand()


print(np.random.rand(5))

# create a NumPy array using numpy.random.randint()


print(np.random.randint(5, size=10))

Output:

[1 2 3 4 5 6 7 8 9]
[ 1. 5.5 10. ]
[0 0 0 0 0]
[1 1 1 1 1]
[0.31447226 0.89090771 0.45908938 0.92006507 0.37757036]
[4 3 2 3 1 2 4 1 4 2]

Example 2: For N-dimensional Numpy Arrays

Initial placeholders for Numpy two dimension arrays can be created by using
various NumPy functions.

Initial Placeholders for 2D Array Example

zeros() np.zeros([4, 3], dtype = np.int32)

ones() np.ones([4, 3], dtype = np.int32)

full() np.full([2, 2], 67, dtype = int)

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 5/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

Initial Placeholders for 2D Array Example

eye() np.eye(4)

Python3

# create a NumPy array using numpy.zeros()


print(np.zeros([4, 3], dtype = np.int32))

# create a NumPy array using numpy.ones()


print(np.ones([4, 3], dtype = np.int32))

# create a NumPy array using numpy.full()


print(np.full([2, 2], 67, dtype = int))

# create a NumPy array using numpy.eye()


print(np.eye(4))

Output:

[[0 0 0]
[0 0 0]
[0 0 0]
[0 0 0]]
[[1 1 1]
[1 1 1]
[1 1 1]
[1 1 1]]
[[67 67]
[67 67]]
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]

3. Inspecting Properties
NumPy arrays possess some basic properties that can be used to get
information about the array such as the size, length, shape, and datatype of
the array. Numpy arrays can also be converted to a list and be change their
datatype.

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 6/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

Inspecting Properties Example

Size arr.size

Length len(arr)

Shape arr.shape

Datatype arr.dtype

Changing Datatype of Array arr.astype(‘float64’)

Converting Array to List arr.tolist()

Example 1: One Dimensional Numpy Array

Python3

arr = np.asarray([1, 2, 3, 4])


# check size of the array
print("Size:", arr.size)

# check len of the array


print("len:", len(arr))

# check shape of the array


print("Shape:", arr.shape)

# check dtype of the array elements


print("Datatype:", arr.dtype)

# change the dtype to 'float64'


arr = arr.astype('float64')
print(arr)
print("Datatype:", arr.dtype)

# convert array to list


lis = arr.tolist()
print("\nList:", lis)
print(type(lis))

Output:
https://www.geeksforgeeks.org/numpy-cheat-sheet/ 7/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

Size: 4
len: 4
Shape: (4,)
Datatype: int64
[1. 2. 3. 4.]
Datatype: float64
List: [1.0, 2.0, 3.0, 4.0]
<class 'list'>

Example 2: N-Dimensional Numpy Array

Python3

# Two dimensional numpy array


list_1 = [1, 2, 3, 4]
list_2 = [5, 6, 7, 8]
list_3 = [9, 10, 11, 12]
arr = np.array([list_1, list_2, list_3])

# check size of the array


print("Size:", arr.size)

# check length of the array


print("Length:", len(arr))

# check shape of the array


print("Shape:", arr.shape)

# check dtype of the array elements


print("Datatype:", arr.dtype)

# change the dtype to 'float64'


arr = arr.astype('float64')
print(arr)
print(arr.dtype)

# convert array to list


lis = arr.tolist()
print("\nList:", lis)
print(type(lis))

Output:

Size: 12
Length: 3
Shape: (3, 4)
Datatype: int64

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 8/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

[[ 1. 2. 3. 4.]
[ 5. 6. 7. 8.]
[ 9. 10. 11. 12.]]
float64
List: [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0,
12.0]]
<class 'list'>

Getting Information on a Numpy Function

The np.info() function is used to get information about any Numpy function,
class, or module along with its parameters, return values, and any other
information.

Python3

import sys
print(np.info(np.add, output=sys.stdout))

Output:

add(x1, x2, /, out=None, *, where=True, casting='same_kind',


order='K',
dtype=None, subok=True[, signature, extobj])
Add arguments element-wise.
Parameters
----------
x1, x2 : array_like
The arrays to be added.
.....

4. Saving and Loading File


Numpy arrays can be stored or loaded from a disk file with the ‘.npy‘
extension. There are various ways by which we can import a text file in a
NumPy array.

Importing & Exporting Example

Saving array on disk np.save(“file”, np.arange(5))

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 9/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

Importing & Exporting Example

Loading a file np.load(“file.npy”)

Importing a Text File np.loadtxt(‘file.txt’)

Importing CSV File np.genfromtxt(‘file.csv’,delimiter=’,’)

Write Text File np.savetxt(‘file.txt’,arr,delimiter=’ ‘)

Saving and loading on Disk

Numpy arrays can be stored on the disk using the save() function and loaded
using the load() function.

Python3

# the array is saved in the file geekfile.npy


np.save("geekfile", np.arange(5))

# the array is loaded into b


print(np.load("geekfile.npy"))

Output:

[0 1 2 3 4]

Saving in a Text File

Numpy arrays can be stored on a text file using the savetxt() function.

Python3

x = np.arange(0, 10, 1)
print(x)

# X array saved in geekfile.txt


c = np.savetxt("geekfile.txt", x, delimiter =', ')

Output:

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 10/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

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

Loading from a Text File

The “myfile.txt” has the following content which is loaded using the
loadtxt() function.

0 1 2
3 4 5

Python3

d = np.loadtxt("myfile.txt")
print(d)

Output:

[[0. 1. 2.]
[3. 4. 5.]]

Loading a CSV file

We can also load a CSV file in Python using Numpy using another method
called genfromtxt() function. The ‘myfilecsv’ has the following content:

1,2,3
4,5,6

Python3

Data = np.genfromtxt("files\myfile.csv", delimiter=",")


print(Data)

Output:

[[1. 2. 3.]
[4. 5. 6.]]

5. Sorting Array
Numpy arrays can be sorted using the sort() method based on their axis.

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 11/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

Sorting NumPy Array Example

Sorting 1D Array arr.sort()

Sorting along the first axis of the 2D array np.sort(a, axis = 0)

Example 1: One-Dimensional array

Python3

# sorting a one dimensional


# numpy array using numpy.sort()
a = np.array([12, 15, 10, 1])
print("Array before sorting",a)
a.sort()
print("Array after sorting",a)

Output:

Array before sorting [12 15 10 1]


Array after sorting [ 1 10 12 15]

Example 2: Two-Dimensional array

Python3

# sorting a two dimensional


# numpy array using numpy.sort()
# sort along the first axis
a = np.array([[12, 15], [10, 1]])
arr1 = np.sort(a, axis = 0)
print ("Along first axis : \n", arr1)

# sort along the last axis


a = np.array([[10, 15], [12, 1]])
arr2 = np.sort(a, axis = -1)
print ("\nAlong Last axis : \n", arr2)

a = np.array([[12, 15], [10, 1]])


arr1 = np.sort(a, axis = None)
print ("\nAlong none axis : \n", arr1)

Output:

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 12/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

Along first axis :


[[10 1]
[12 15]]
Along Last axis :
[[10 15]
[ 1 12]]
Along none axis :
[ 1 10 12 15]

6. NumPy Array Manipulation


NumPy provides a variety of ways by which we can manipulate NumPy
arrays to change their shape or size.

NumPy Array Manipulation Example

Append at the end of the 1D array np.append(arr, [7])

col = np.arange(5,
Append to 2D array column wise 11).reshape(1, 6)

np.append(arr, col, axis=0)

row = np.array([1,
Append to 2D array row-wise 2]).reshape(2, 1)

np.append(arr, row, axis=1)

Inserting an element at a particular index of


np.insert(arr, 1, 9)
a 1D array

Inserting an element at a particular index of


np.insert(arr, 1, 9, axis = 1)
a 2D array

Delete an element from the 1D array np.delete(arr, object)

Delete an element from the 2D array np.delete(arr, object, axis=1)

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 13/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

NumPy Array Manipulation Example

Reshaping the 1D array to a 2D array np.reshape(n, m)

Reshaping the 2D array to a 1D array arr.reshape((12))

Resizing array arr.resize(3, 4)

Flattening array arr.flatten()

Transposing array arr.transpose(1, 0)

Appending Elements to Array

Numpy arrays can be manipulated by appending the new values at the end
of the array using the append() function

Example 1: One-Dimensional Array

Python3

# Adding the values at the end


# of a numpy array
print("Original Array:", arr)

# appending to the array


arr = np.append(arr, [7])
print("Array after appending:", arr)

Output:

Original Array: [[ 1. 2. 3. 4.]


[ 5. 6. 7. 8.]
[ 9. 10. 11. 12.]]
Array after appending: [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.
12. 7.]

Example 2: N-Dimensional Array

Python3
https://www.geeksforgeeks.org/numpy-cheat-sheet/ 14/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

# Adding the values at the end


# of a numpy array
arr = np.arange(1, 13).reshape(2, 6)
print("Original Array")
print(arr, "\n")

# create another array which is


# to be appended column-wise
col = np.arange(5, 11).reshape(1, 6)
arr_col = np.append(arr, col, axis=0)
print("Array after appending the values column wise")
print(arr_col, "\n")

# create an array which is


# to be appended row wise
row = np.array([1, 2]).reshape(2, 1)
arr_row = np.append(arr, row, axis=1)
print("Array after appending the values row wise")
print(arr_row)

Output:

Original Array
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]
Array after appending the values column wise
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]
[ 5 6 7 8 9 10]]
Array after appending the values row wise
[[ 1 2 3 4 5 6 1]
[ 7 8 9 10 11 12 2]]

Inserting Elements into the Array

Numpy arrays can be manipulated by inserting them at a particular index


using insert() function.

Example 1: One-Dimensional Array

Python3

arr = np.asarray([1, 2, 3, 4])


# Python Program illustrating numpy.insert()
print("1D arr:", arr)
print("Shape:", arr.shape)

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 15/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

# Inserting value 9 at index 1


a = np.insert(arr, 1, 9)
print("\nArray after insertion:", a)
print("Shape:", a.shape)

Output:

1D arr: [1 2 3 4]
Shape: (4,)
Array after insertion: [1 9 2 3 4]
Shape: (5,)

Removing Elements from Numpy Array

Elements from a NumPy array can be removed using the delete() function.

Example 1: One-Dimensional Array

Python3

# Python Program illustrating


# numpy.delete()
print("Original arr:", arr)
print("Shape : ", arr.shape)

# deletion from 1D array


object = 2
a = np.delete(arr, object)
print("\ndeleteing the value at index {} from array:\n {}".format(object,a))
print("Shape : ", a.shape)

Output:

Original arr: [1 2 3 4]
Shape : (4,)
deleteing the value at index 2 from array:
[1 2 4]
Shape : (3,)

Reshaping Array

NumPy arrays can be reshaped, which means they can be converted from
one dimension array to an N-dimension array and vice-versa using the
https://www.geeksforgeeks.org/numpy-cheat-sheet/ 16/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

reshape() method. The reshape() function does not change the original array.

Example 1: Reshaping NumPy one-dimension array to a two-dimension


array

Python3

# creating a numpy array


array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])

# printing array
print("Array: " + str(array))

# reshaping numpy array


# converting it to 2-D from 1-D array
reshaped1 = array.reshape((4, array.size//4))

# printing reshaped array


print("First Reshaped Array:")
print(reshaped1)

# creating another reshaped array


reshaped2 = np.reshape(array, (2, 8))

# printing reshaped array


print("\nSecond Reshaped Array:")
print(reshaped2)

Output:

Array: [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]
First Reshaped Array:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]
Second Reshaped Array:
[[ 1 2 3 4 5 6 7 8]
[ 9 10 11 12 13 14 15 16]]

Example 2: Reshaping NumPy from a two dimension array to a one-


dimension array.

Python3

# printing array
print(" 2-D Array:")

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 17/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

print(arr)

# reshaping numpy array


# converting it to 1-D from 2-D array
reshaped = arr.reshape((12))

# printing reshaped array


print("Reshaped 1-D Array:")
print(reshaped)

Output:

2-D Array:
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]
Reshaped 1-D Array:
[ 1 2 3 4 5 6 7 8 9 10 11 12]

Resizing an Array

Numpy arrays can be resized using the resize() function. It returns nothing
but changes the original array.

Python3

# Making a random array


arr = np.array([1, 2, 3, 4, 5, 6])
# Required values 12, existing values 6
arr.resize(3, 4)
print(arr)

Output:

[[1 2 3 4]
[5 6 0 0]
[0 0 0 0]]

Flatten a Two Dimensional array

The flatten() function of Numpy module is used to convert a 2-dimensional


array to a 1-dimensional array. It returns a copy of the original array.

Python3

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 18/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

# Two dimensional numpy array


list_1 = [1, 2, 3, 4]
list_2 = [5, 6, 7, 8]
arr = np.array([list_1, list_2])

print(arr.flatten())

Output:

[1 2 3 4 5 6 7 8]

Transpose

Numpy two-dimensional array can be transposed using the transpose()


function.

Python3

# making a 3x3 array


gfg = np.array([[1, 2],
[4, 5],
[7, 8]])

# before transpose
print(gfg, end ='\n\n')

# after transpose
print(gfg.transpose(1, 0))

Output:

[[1 2]
[4 5]
[7 8]]
[[1 4 7]
[2 5 8]]

7. Combining and Splitting Commands

Combining and Splitting Example

Combining Arrays np.concatenate((arr1, arr2), axis = 0)

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 19/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

Combining and Splitting Example

Splitting array np.split(arr, 3, 1)

Horizontal Split np.hsplit(arr, 3)

Vertical Split np.vsplit(a, 3)

Combining Numpy Arrays

Combining two arrays into a single Numpy array can be done using
concatenate() method.

Python3

arr1 = np.array([[2, 4], [6, 8]])


arr2 = np.array([[3, 5], [7, 9]])

# combining on axis 0
gfg = np.concatenate((arr1, arr2), axis = 0)
print(gfg)

# combining on axis 1
gfg = np.concatenate((arr1, arr2), axis = 1)
print("\n", gfg)

# combining on axis None


gfg = np.concatenate((arr1, arr2), axis = None)
print("\n", gfg)

# stacking two arrays on one another


print(np.stack((arr1, arr2), axis=1))

Output:

[[2 4]
[6 8]
[3 5]
[7 9]]
[[2 4 3 5]
[6 8 7 9]]
[2 4 6 8 3 5 7 9]
[[[2 4]
https://www.geeksforgeeks.org/numpy-cheat-sheet/ 20/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

[3 5]]
[[6 8]
[7 9]]]

Splitting Numpy Arrays

Example 1: using split()

Numpy arrays can be split into multiple arrays horizontally or vertically.

Python3

# Making of a 3x3 array


a = np.arange(9).reshape(3, 3)
print(a)

# Horizontal splitting of array 'a'


# using 'split' with axis parameter = 1.
print("Splitted array in horizontal form:\n", np.split(a, 3, 1))

# Vertical splitting of array 'a'


# using 'split' with axis parameter = 0.
print("\nSplitted array in vertical form:\n", np.split(a, 3, 0))

Output:

[[0 1 2]
[3 4 5]
[6 7 8]]
Splitted array in horizontal form:
[array([[0],
[3],
[6]]), array([[1],
[4],
[7]]), array([[2],
[5],
[8]])]
Splitted array in vertical form:
[array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])]

Example 2: using hsplit()

The hsplit() splits the Numpy array in multiple horizontal arrays.

Python3

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 21/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

# Horizontal splitting of array


# 'a' using np.hsplit().
print(a)
print("Splitted array in horizontally to form:", np.hsplit(a, 3))

Output:

[[0 1 2]
[3 4 5]
[6 7 8]]
Splitted array in horizontally to form: [array([[0],
[3],
[6]]), array([[1],
[4],
[7]]), array([[2],
[5],
[8]])]

Example 3: using vsplit()

The vsplit() splits the Numpy array into multiple vertical arrays.

Python3

# Vertical splitting of array 'a'


# using np.vsplit().
print("Splitted array in vertically to form:", np.vsplit(a, 3))

Output:

Splitted array in vertically to form:


[array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])]

8. Indexing, Slicing and Subsetting


Different ways of Indexing the Numpy array are as follows:

Indexing, Slicing and Subsetting Example

Subsetting arr[np.array([1, 3, -3])]

Sclicing arr[-2:7:1]

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 22/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

Indexing, Slicing and Subsetting Example

Integer Indexing a[[0 ,1 ,2 ],[0 ,0 ,1]]

Boolean Indexing a[a>50]

Subsetting Numpy Array

Python3

# Index values can be negative.


print(arr)
print("Elements are:", arr[np.array([1, 3, -3])])

Output:

[1 2 3 4 7]
Elements are: [2 4 3]

Slicing Numpy Array

The “:” operator means all elements till the end.

Python3

print(arr)

# a[start:stop:step]
print("a[-2:7:1] = ",arr[-2:7:1])

print("a[1:] = ",arr[1:])

Output:

[1 2 3 4 7]
a[-2:7:1] = [4 7]
a[1:] = [2 3 4 7]

Indexing Numpy Array

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 23/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

Numpy array indexing is of two types: Integer indexing and Boolean


indexing.

Python3

# Integer Indexing
a = np.array([[1 ,2 ],[3 ,4 ],[5 ,6 ]])
print(a[[0 ,1 ,2 ],[0 ,0 ,1]])

# Boolean Indexing
a = np.array([10, 40, 80, 50, 100])
print(a[a>50])

Output:

[1 3 6]
[ 80 100]

9. Copying and Viewing Array


NumPy arrays can be manipulated with and without making a copy of an
array object. When an array is copied with a normal assignment, it uses the
exact same id as the original array. Whereas when a deep copy of the array
object is made, a completely new array is created with a different id. This
does not affect the original array when any changes are made to the newly
copied array.

Copying and Viewing Array Example

Coping to new memory space arr.copy()

Shallow Copy arr.view()

Copying Array

Let us see different ways of copying and viewing numpy arrays.

Shallow copy

Python3

# Copying Numpy array with normal assignment


nc = arr
https://www.geeksforgeeks.org/numpy-cheat-sheet/ 24/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

# both arr and nc have same id


print("Normal Assignment copy")
print("id of arr:", id(arr))
print("id of nc:", id(nc))

# updating nc
nc[0]= 12

# printing the values


print("original array:", arr)
print("assigned array:", nc)

Output:

Normal Assignment copy


id of arr: 139656514595568
id of nc: 139656514595568
original array: [12 2 3 4]
assigned array: [12 2 3 4]

Deep Copy

Python3

# Creating a different copy of NumPy


# array creating copy of array
c = arr.copy()

# both arr and c have different id


print("id of arr:", id(arr))
print("id of c:", id(c))

# changing original array


# this will not effect copy
arr[0] = 12

# printing array and copy


print("original array:", arr)
print("copy:", c)

Output:

id of arr: 139656514596912
id of c: 139656514596432
original array: [12 2 3 4]
copy: [1 2 3 4]

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 25/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

Viewing Array

The view is also known as a shallow copy which is just a view of the original
array. It has a separate id but any changes made to the original will also
reflect on the view.

Python3

# Creating a view of a
# NumPy array
# creating view
v = arr.view()

# both arr and v have different id


print("id of arr:", id(arr))
print("id of v:", id(v))

# changing original array


# will effect view
arr[0] = 12

# printing array and view


print("original array:", arr)
print("view:", v)

Output:

id of arr: 139656514598640
id of v: 139656514599216
original array: [12 2 3 4]
view: [12 2 3 4]

10. NumPy Array Mathematics

Arithmetic Operations

Numpy arrays can perform arithmetic operations like addition, subtraction,


multiplication, division, mod, remainder, and power.

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 26/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

Arithmetic Operations Example

Adds
np.add(a, b)
elements of 2 Array

Substracts
np.subtract(a, b)
elements of 2 Array

Multiply
np.multiply(a, b)
elements of 2 Array

Divide
np.divide(a, b)
elements of 2 Array

Modulo
np.mod(a, b)
of elements of 2 Array

Remainder
np.remainder(a,b)
of elements of 2 Array

Power
np.power(a, b)
of elements of 2 Array

Exponant
np.exp(b)
value of elements of 2 Array

Python3

# Defining both the matrices


a = np.array([5, 72, 13, 100])
b = np.array([2, 5, 10, 30])

# Performing addition using numpy function


print("Addition:", np.add(a, b))

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 27/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

# Performing subtraction using numpy function


print("Subtraction:", np.subtract(a, b))

# Performing multiplication using numpy function


print("Multiplication:", np.multiply(a, b))

# Performing division using numpy functions


print("Division:", np.divide(a, b))

# Performing mod on two matrices


print("Mod:", np.mod(a, b))

#Performing remainder on two matrices


print("Remainder:", np.remainder(a,b))

# Performing power of two matrices


print("Power:", np.power(a, b))

# Performing Exponentiation
print("Exponentiation:", np.exp(b))

Output:

Addition: [ 7 77 23 130]
Subtraction: [ 3 67 3 70]
Multiplication: [ 10 360 130 3000]
Division: [ 2.5 14.4 1.3 3.33333333]
Mod: [ 1 2 3 10]
Remainder: [ 1 2 3 10]
Power: [ 25 1934917632 137858491849
1152921504606846976]
Exponentiation: [7.38905610e+00 1.48413159e+02 2.20264658e+04
1.06864746e+13]

Comparison

Numpy array elements can be compared with another array using the
array_equal() function.

Python3

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


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

comparison = an_array == another_array


equal_arrays = comparison.all()

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 28/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

print(equal_arrays)

Output:

True

Vector Math

Numpy arrays can also determine square root, log, absolute, sine, ceil, floor,
and round values.

Vector Math Example

Square root
np.sqrt(arr)
of each element

Log
np.log(arr)
value of each element

Absolute
np.absolute(arr)
value of each element

Sine
np.sin(arr)
value of each element

Ceil
np.ceil(arr)
value of each element

Floor
np.floor(arr)
value of each element

Round
np.round_(arr)
value of each element

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 29/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

Python3

arr = np.array([.5, 1.5, 2.5, 3.5, 4.5, 10.1])

# applying sqrt() method


print("Square-root:", np.sqrt(arr))

# applying log() method


print("Log Value: ", np.log(arr))

# applying absolute() method


print("Absolute Value:", np.absolute(arr))

# applying sin() method


print("Sine values:", np.sin(arr))

# applying ceil() method


print("Ceil values:", np.ceil(arr))

# applying floor() method


print("Floor Values:", np.floor(arr))

# applying round_() method


print ("Rounded values:", np.round_(arr))

Output:

Square-root: [0.70710678 1.22474487 1.58113883 1.87082869 2.12132034


3.17804972]
Log Value: [-0.69314718 0.40546511 0.91629073 1.25276297
1.5040774 2.31253542]
Absolute Value: [ 0.5 1.5 2.5 3.5 4.5 10.1]
Sine values: [ 0.47942554 0.99749499 0.59847214 -0.35078323
-0.97753012 -0.62507065]
Ceil values: [ 1. 2. 3. 4. 5. 11.]
Floor Values: [ 0. 1. 2. 3. 4. 10.]
Rounded values: [ 0. 2. 2. 4. 4. 10.]

Statistic

Numpy arrays also perform statistical functions such as mean, summation,


minimum, maximum, standard deviation, var, and correlation coefficient.

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 30/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

Statistic Example

Mean np.mean(arr)

Median np.median(arr)

Summation np.sum(arr, dtype = np.uint8)

Maximum np.max(arr)

Minimum value np.min(arr)

Variance np.var(arr, dtype = np.float32)

Standard Deviation np.std(arr, dtype = np.float32)

Correlation Coefficient np.corrcoef(array1, array2)

Python3

# 1D array
arr = [20, 2, 7, 1, 34]

# mean
print("mean of arr:", np.mean(arr))

# median
print("median of arr:", np.median(arr))

# sum
print("Sum of arr(uint8):", np.sum(arr, dtype = np.uint8))
print("Sum of arr(float32):", np.sum(arr, dtype = np.float32))

# min and max


print("maximum element:", np.max(arr))
print("minimum element:", np.min(arr))

# var
print("var of arr:", np.var(arr))
print("var of arr(float32):", np.var(arr, dtype = np.float32))

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 31/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

# standard deviation
print("std of arr:", np.std(arr))
print ("More precision with float32", np.std(arr, dtype = np.float32))

Output:

mean of arr: 12.8


median of arr: 7.0
Sum of arr(uint8): 64
Sum of arr(float32): 64.0
maximum element: 34
minimum element: 1
var of arr: 158.16
var of arr(float32): 158.16
std of arr: 12.576167937809991
More precision with float32 12.576168

corrcoef

Python3

# create numpy 1d-array


array1 = np.array([0, 1, 2])
array2 = np.array([3, 4, 5])

# pearson product-moment correlation


# coefficients of the arrays
rslt = np.corrcoef(array1, array2)

print(rslt)

Output:

[[1. 1.]
[1. 1.]]

Benefits of Using NumPy Cheat Sheet


NumPy Cheat Sheet comes with advantages that make it essential for
Python programmers and data scientists. Here are some of the key benefits
of NumPy:

1. Efficient Data Handling: NumPy provides a robust framework for


handling large datasets efficiently, enabling faster data processing and

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 32/38
10/23/24, 12:46 AM NumPy Cheat Sheet: Beginner to Advanced (PDF)

manipulation.
2. Mathematical Functions: The library includes an extensive collection of
mathematical functions for operations like trigonometry, statistics, linear
algebra, and more.
3. Broadcasting: NumPy allows broadcasting, which enables element-wise
operations on arrays of different shapes, reducing the need for explicit
loops.
4. Interoperability: It integrates with other libraries like Pandas, SciPy, and
Matplotlib, improving its functionality for data analysis and visualization.
5. Memory Optimization: NumPy optimizes memory usage, making it ideal
for working with large datasets without consuming excessive RAM.
6. Multidimensional Arrays: The library supports multidimensional arrays,
enabling easy manipulation of complex data structures.
7. Open-source and Community Support: NumPy is open-source, and its
active community provides regular updates, bug fixes, and additional
functionalities.

Applications of NumPy
The various applications of Numpy other than data analysis are given below

Scientific Computing
Data Analysis and Preprocessing
Image Processing
Machine Learning
Signal Processing

Feature of NumPy
Here are some features of Numpy that why Numpy is famous for data
analysis and scientific computing

It is a powerful N-dimensional array object “ndarray“.


Numpy offers a wide range of collections of Mathematical Functions.
It easily Integrates with low-level languages such as C/C++ and Fortran
Also.
It offers a comprehensive range of broadcasting functions for dealing with
arrays of different dimensions.

Conclusion

https://www.geeksforgeeks.org/numpy-cheat-sheet/ 33/38

You might also like