0% found this document useful (0 votes)
5 views44 pages

Numpy

NumPy is a Python library for efficient array manipulation and supports various mathematical functions, including linear algebra and Fourier transforms. It provides a fast alternative to Python lists by storing data in contiguous memory locations, making operations up to 50 times faster. The main object in NumPy is the ndarray, which can be created from lists, tuples, or other array-like objects, and can have multiple dimensions.
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)
5 views44 pages

Numpy

NumPy is a Python library for efficient array manipulation and supports various mathematical functions, including linear algebra and Fourier transforms. It provides a fast alternative to Python lists by storing data in contiguous memory locations, making operations up to 50 times faster. The main object in NumPy is the ndarray, which can be created from lists, tuples, or other array-like objects, and can have multiple dimensions.
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/ 44

NUMPY

NumPy is a Python library used for working with arrays.

It also has functions for working in domain of linear algebra, fourier transform, and matrices.

NumPy was created in 2005 by Travis Oliphant. It is an open source project and you can use it freely.

NumPy stands for Numerical Python.

In Python we have lists that serve the purpose of arrays, but they are slow to process.

NumPy aims to provide an array object that is up to 50x faster than traditional Python lists.

Why is NumPy Faster Than Lists? NumPy arrays are stored at one continuous place in memory unlike
lists, so processes can access and manipulate them very efficiently.

This behavior is called locality of reference in computer science.

This is the main reason why NumPy is faster than lists. Also it is optimized to work with latest CPU
architectures.

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. Example:

In this example, we are creating a two-dimensional array that has the rank of 2 as it has 2 axes.

The first axis(dimension) is of length 2, i.e., the number of rows, and the second axis(dimension) is of
length 3, i.e., the number of columns. The overall shape of the array can be represented as (2, 3)

In [2]:
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: int64

Create a NumPy ndarray Object: NumPy is used to work with arrays. The array object in NumPy is
called ndarray.

We can create a NumPy ndarray object by using the array() function.

In [1]: import numpy as np

# Create a numpy array


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

# Print the array


print(arr)

# Print the type of the array


print(type(arr))

[1 2 3 4 5]
<class 'numpy.ndarray'>

To create an ndarray, we can pass a list, tuple, set or any array-like object into the array() method, and it
will be converted into an ndarray:

Example Use a tuple to create a NumPy array:

In [3]:
import numpy as np

# Creating array from list with type float


a = np.array([[1, 2, 4], [5, 8, 7]])
print ("Array created using passed list:\n", a)

# Creating array from tuple


b = np.array((1 , 3, 2))
print ("\nArray created using passed tuple:\n", b)

Array created using passed list:


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

Array created using passed tuple:


[1 3 2]

Create Array of Fixed Size


Often, the element is of an array is originally unknown, but its size is known. Hence, NumPy offers
several functions to create arrays with initial placeholder content.

This minimize the necessity of growing arrays, an expensive operation. For example: np.zeros, np.ones,
np.full, np.empty, etc.

To create sequences of numbers, NumPy provides a function analogous to the range that returns
arrays instead of lists.
In [6]:
# Creating a 3X4 array with all zeros
c = np.zeros((3, 4))
print ("An array initialized with all zeros:\n", c)

# Create a constant value array of complex type


d = np.full((3, 3), 6, dtype = 'complex')
print ("An array initialized with all 6s."
"Array type is complex:\n", d)

# Create an array with random values


e = np.random.random((2, 2))
print ("A random array:\n", e)

An array initialized with all zeros:


[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
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.81386092 0.8669814 ]
[0.48205695 0.00147063]]

Create Using arange() Function arange(): This function returns evenly spaced values within a given
interval. Step size is specified.

In [3]:
# Create a sequence of integers
# from 0 to 30 with steps of 5
import numpy as np

# Create a sequence of integers from 0 to 30 with steps of 5


f = np.arange(0, 30, 5)

# Print the sequential array


print("A sequential array with steps of 5:\n", f)

A sequential array with steps of 5:


[ 0 5 10 15 20 25]

Create Using linspace() Function linspace(): It returns evenly spaced values within a given interval.

In [9]:
import numpy as np

# Create a sequence of 10 values in the range 0 to 5


g = np.linspace(0, 5, 10)

# Print the sequential array


print("A sequential array with 10 values between 0 and 5:\n", g)

A sequential array with 10 values between0 and 5:


[0. 0.55555556 1.11111111 1.66666667 2.22222222 2.77777778
3.33333333 3.88888889 4.44444444 5. ]
In [4]:
# 0 Dimensional Array
import numpy as np

# Create a 0-dimensional array


arr = np.array(42)

# Print the array


print(arr)

42

In [5]: # One Dimensional Array


import numpy as np

# Create a list
list1 = [1, 2, 3, 4, 5]

# Convert the list to a numpy array


arr1 = np.array(list1)

# Print the array


print(arr1)

[1 2 3 4 5]

In [6]:
# Type
import numpy as np

# Create a list
list1 = [1, 2, 3, 4, 5]

# Convert the list to a numpy array


arr1 = np.array(list1)

# Print the type of the array


print(type(arr1))

<class 'numpy.ndarray'>

In [7]: import numpy as np

# Create a numpy array


arr2 = np.array([10, 20, 30, 40])

# Print the array


print(arr2)

[10 20 30 40]

In [8]: # Two Dimensional Array


import numpy as np
# Create a two-dimensional numpy array
arr1 = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]
])

# Print the array


print(arr1)

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

In [9]:
import numpy as np

# Create a two-dimensional numpy array


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

# Print the size of the array


print(arr1.size)

12

In [10]: import numpy as np

# Create a two-dimensional numpy array


arr2 = np.array([
[10, 20, 30],
[40, 50, 60]
])

# Print the array


print(arr2)

[[10 20 30]
[40 50 60]]

In [11]:
import numpy as np

# Create a two-dimensional numpy array


arr2 = np.array([
[10, 20, 30],
[40, 50, 60]
])
# Print the size of the array
print(arr2.size)

In [12]: # Three Dimensional Array


import numpy as np

# Create a three-dimensional numpy array


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

# Print the array


print(arr1)

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

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

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

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

Check Number of Dimensions?

NumPy Arrays provides the ndim attribute that returns an integer that tells us how many dimensions
the array have.

In [13]: import numpy as np

# Create different dimensional numpy arrays


a = np.array(42) # 0-dimensional array
b = np.array([1, 2, 3, 4, 5]) # 1-dimensional array
c = np.array([[1, 2, 3], [4, 5, 6]]) # 2-dimensional array
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]]) # 3-dimensi

# Print the number of dimensions of each array


print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)

0
1
2
3

Higher Dimensional Arrays

An array can have any number of dimensions.

When the array is created, you can define the number of dimensions by using the ndmin argument.

Example Create an array with 5 dimensions and verify that it has 5 dimensions:

In [14]:
import numpy as np

# Create a numpy array with a minimum of 5 dimensions


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

# Print the array


print(arr)

# Print the number of dimensions of the array


print('number of dimensions :', arr.ndim)

[[[[[1 2 3 4]]]]]
number of dimensions : 5

NumPy Array Indexing

Access Array Elements Array indexing is the same as accessing an array element.

You can access an array element by referring to its index number.

The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second
has index 1 etc.

In [15]: import numpy as np

# Create a numpy array


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

# Print the first element of the array


print(arr[0])

In [16]: import numpy as np

# Create a numpy array


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

# Print the sum of the third and fourth elements of the array
print(arr[2] + arr[3])

7
Access 2-D Arrays To access elements from 2-D arrays we can use comma separated integers
representing the dimension and the index of the element.

Think of 2-D arrays like a table with rows and columns, where the dimension represents the row and
the index represents the column.

Example Access the element on the first row, second column:

In [17]:
import numpy as np

# Create a two-dimensional numpy array


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

# Print the 2nd element on the 1st row


print('2nd element on 1st row: ', arr[0, 1])

2nd element on 1st row: 2

In [18]:
import numpy as np

# Create a two-dimensional numpy array


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

# Print the 5th element on the 2nd row


print('5th element on 2nd row: ', arr[1, 4])

5th element on 2nd row: 10

Access 3-D Arrays To access elements from 3-D arrays we can use comma separated integers
representing the dimensions and the index of the element.

Example Access the third element of the second array of the first array:

In [19]:
import numpy as np

# Create a three-dimensional numpy array


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

# Print the element at position (0, 1, 2)


print(arr[0, 1, 2])

Negative Indexing Use negative indexing to access an array from the end.

Example Print the last element from the 2nd dim:

In [20]:
import numpy as np

# Create a two-dimensional numpy array


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

# Print the last element from the 2nd dimension


print('Last element from 2nd dim: ', arr[1, -1])
Last element from 2nd dim: 10

NumPy Array Slicing


Slicing arrays Slicing in python means taking elements from one given index to another given index.

We pass slice instead of index like this: [start:end].

We can also define the step, like this: [start:end:step].

If we don't pass start its considered 0

If we don't pass end its considered length of array in that dimension

If we don't pass step its considered 1

Note: The result includes the start index, but excludes the end index.

In [21]: # Example
# Slice elements from index 1 to index 5 from the following array:
import numpy as np

# Create a numpy array


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

# Print the sliced elements from index 1 to index 5


print(arr[1:5])

[2 3 4 5]

In [22]:
# Example
# Slice elements from index 4 to the end of the array
import numpy as np

# Create a numpy array


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

# Print the sliced elements from index 4 to the end of the array
print(arr[4:])

[5 6 7]

In [23]:
# Example
# Slice elements from the beginning to index 4 (not included):

import numpy as np

# Create a numpy array


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

# Print the sliced elements from the beginning to index 4 (not included)
print(arr[:4])

[1 2 3 4]
Negative Slicing
Use the minus operator to refer to an index from the end:

In [24]:
# Example
# Slice from the index 3 from the end to index 1 from the end:
import numpy as np

# Create a numpy array


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

# Print the sliced elements from index 3 from the end to index 1 from the e
print(arr[-3:-1])

[5 6]

STEP
Use the step value to determine the step of the slicing:

In [25]:
# Example
# Return every other element from index 1 to index 5:

import numpy as np

# Create a numpy array


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

# Print every other element from index 1 to index 5


print(arr[1:5:2])

[2 4]

In [26]:
# Example
# Return every other element from the entire array:

import numpy as np

# Create a numpy array


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

# Print every other element from the entire array


print(arr[::2])

[1 3 5 7]

Slicing 2-D Arrays


In [93]:
# Example
# From the second element, slice elements from index 1 to index 4 (not incl
import numpy as np

# Create a 2-D numpy array


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

# Slice the array to get elements from index 1 to index 4 (not included) of
print(arr[1, 1:4])

[7 8 9]

In [92]:
import numpy as np

# Create a 2-D numpy array


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

# Slice the array to get the element at column index 2 from rows 0 to 1
print(arr[0:2, 2])

[3 8]

In [91]:
import numpy as np

# Create a 2-D numpy array


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

# Slice the array to get elements from row 0 to 1 and columns 1 to 3


print(arr[0:2, 1:4])

[[2 3 4]
[7 8 9]]

NumPy Data Types


Data Types in Python By default Python have these data types:

strings - used to represent text data, the text is given under quote marks. e.g. "ABCD" integer - used to
represent integer numbers. e.g. -1, -2, -3 float - used to represent real numbers. e.g. 1.2, 42.42 boolean -
used to represent True or False. complex - used to represent complex numbers. e.g. 1.0 + 2.0j, 1.5 +
2.5j

Data Types in NumPy NumPy has some extra data types, and refer to data types with one character,
like i for integers, u for unsigned integers etc.

Below is a list of all data types in NumPy and the characters used to represent them.

i - integer b - boolean u - unsigned integer f - float c - complex float m - timedelta M - datetime O -


object S - string U - unicode string V - fixed chunk of memory for other type ( void )

Checking the Data Type of an Array The NumPy array object has a property called dtype that returns
the data type of the array:
In [90]:
# Example
# Get the data type of an array object:
import numpy as np

# Create a numpy array with integer values


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

# Print the data type of the array


print(arr.dtype)

int64

In [89]:
import numpy as np

# Create a numpy array with string values


arr = np.array(['apple', 'banana', 'cherry'])

# Print the data type of the array


print(arr.dtype)

<U6

In [88]:
import numpy as np

# Create a numpy array with float values


arr1 = np.array([1.1, 2.1, 3.1, 4.1, 5.1])

# Print the array


print(arr1)

# Print the data type of the array


print(arr1.dtype)

[1.1 2.1 3.1 4.1 5.1]


float64

In [87]:
import numpy as np

# Create a numpy array with boolean values


arr1 = np.array([True, False, False])

# Print the array


print(arr1)

# Print the data type of the array


print(arr1.dtype)

[ True False False]


bool

Creating Arrays With a Defined Data Type


We use the array() function to create arrays, this function can take an optional argument: dtype that
allows us to define the expected data type of the array elements:

In [86]:
# Example
# Create an array with data type string:
import numpy as np

# Create a numpy array with data type string


arr = np.array([1, 2, 3, 4], dtype='S')

# Print the array


print(arr)

# Print the data type of the array


print(arr.dtype)

[b'1' b'2' b'3' b'4']


|S1

For i, u, f, S and U we can define size as well.

In [85]:
# Example
# Create an array with data type 4 bytes integer:
import numpy as np

# Create a numpy array with data type 4 bytes integer


arr = np.array([1, 2, 3, 4], dtype='i4')

# Print the array


print(arr)

# Print the data type of the array


print(arr.dtype)

[1 2 3 4]
int32

Converting Data Type on Existing Arrays


The best way to change the data type of an existing array, is to make a copy of the array with the
astype() method.

The astype() function creates a copy of the array, and allows you to specify the data type as a
parameter.

The data type can be specified using a string, like 'f' for float, 'i' for integer etc. or you can use the data
type directly like float for float and int for integer.

In [84]:
# Example
# Change data type from float to integer by using 'i' as parameter value:
import numpy as np

# Create a numpy array with float values


arr = np.array([1.1, 2.1, 3.1])

# Change the data type of the array to integer using 'i' as parameter value
newarr = arr.astype('i')

# Print the new array


print(newarr)

# Print the data type of the new array


print(newarr.dtype)

[1 2 3]
int32

In [83]:
# Example
# Change data type from integer to boolean:
import numpy as np

# Create a numpy array


arr = np.array([1, 0, 3])

# Change the data type of the array to boolean


newarr = arr.astype(bool)

# Print the new array


print(newarr)

# Print the data type of the new array


print(newarr.dtype)

[ True False True]


bool

NumPy Array Copy vs View


The Difference Between Copy and View The main difference between a copy and a view of an array is
that the copy is a new array, and the view is just a view of the original array.

The copy owns the data and any changes made to the copy will not affect original array, and any
changes made to the original array will not affect the copy.

The view does not own the data and any changes made to the view will affect the original array, and
any changes made to the original array will affect the view.

COPY:

In [82]:
# Example
import numpy as np

# Create a numpy array


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

# Create a copy of the array


x = arr.copy()

# Change the first element of the original array


arr[0] = 42

# Print the original array


print(arr)

# Print the copy


print(x)

[42 2 3 4 5]
[1 2 3 4 5]

The copy SHOULD NOT be affected by the changes made to the original array.

VIEW:

In [81]:
# Example
# Make a view, change the original array, and display both arrays:
import numpy as np

# Create a numpy array


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

# Create a view of the array


x = arr.view()

# Change the first element of the original array


arr[0] = 42

# Print the original array


print(arr)

# Print the view


print(x)

[42 2 3 4 5]
[42 2 3 4 5]

The view SHOULD be affected by the changes made to the original array.

Make Changes in the VIEW:

In [80]:
# Example
# Make a view, change the view, and display both arrays:
import numpy as np

# Create a numpy array


arr = np.array([1, 2, 3, 4, 5])
# Create a view of the array
x = arr.view()

# Change the first element of the view


x[0] = 31

# Print the original array


print(arr)

# Print the view


print(x)

[31 2 3 4 5]
[31 2 3 4 5]

The original array SHOULD be affected by the changes made to the view

Check if Array Owns its Data


As mentioned above, copies owns the data, and views does not own the data, but how can we check
this?

Every NumPy array has the attribute base that returns None if the array owns the data.

Otherwise, the base attribute refers to the original object.

In [79]:
# Example
# Print the value of the base attribute to check if an array owns its data
import numpy as np

# Create a numpy array


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

# Create a copy of the array


x = arr.copy()

# Create a view of the array


y = arr.view()

# Print the base attribute of the copy


print(x.base)

# Print the base attribute of the view


print(y.base)

None
[1 2 3 4 5]

The copy returns None. The view returns the original array.
NumPy Array Shape

Shape of an Array The shape of an array is the number of elements in each dimension.

Get the Shape of an Array NumPy arrays have an attribute called shape that returns a tuple with each
index having the number of corresponding elements.

In [78]:
# Example
# Print the shape of a 2-D array:
import numpy as np

# Create a 2-D numpy array


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

# Print the shape of the array


print(arr.shape)

(2, 4)

The example above returns (2, 4), which means that the array has 2 dimensions, where the first
dimension has 2 elements and the second has 4.

In [77]:
import numpy as np

# Create a 1-D numpy array


arr2 = np.array([10, 20, 30, 40])

# Print the shape of the array


print(np.shape(arr2))

(4,)

In [76]:
import numpy as np

# Create a 3-D numpy array


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

# Print the shape of the array


print(np.shape(arr1))

(4, 4, 3)

In [75]:
# Example
# Create an array with 5 dimensions using ndmin using a vector with values
import numpy as np
# Create a numpy array with 5 dimensions
arr = np.array([1, 2, 3, 4], ndmin=5)

# Print the array


print(arr)

# Print the shape of the array


print('shape of array :', arr.shape)

[[[[[1 2 3 4]]]]]
shape of array : (1, 1, 1, 1, 4)

NumPy Array Reshaping


Reshaping arrays Reshaping means changing the shape of an array.

The shape of an array is the number of elements in each dimension.

By reshaping we can add or remove dimensions or change number of elements in each dimension.

Reshape From 1-D to 2-D Example Convert the following 1-D array with 12 elements into a 2-D array.

The outermost dimension will have 4 arrays, each with 3 elements:

In [74]:
import numpy as np

# Create a 1-D numpy array


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

# Reshape the array to 2-D with shape (4, 3)


newarr = arr.reshape(4, 3)

# Print the original array and its shape


print(arr)
print(np.shape(arr))

# Print the reshaped array and its shape


print(newarr)
print(np.shape(newarr))

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

Reshape From 1-D to 3-D Example Convert the following 1-D array with 12 elements into a 3-D array.

The outermost dimension will have 2 arrays that contains 3 arrays, each with 2 elements:

In [73]:
import numpy as np

# Create a 1-D numpy array


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

# Reshape the array to 3-D with shape (2, 3, 2)


newarr = arr.reshape(2, 3, 2)

# Print the original array and its shape


print(arr)
print(np.shape(arr))

# Print the reshaped array and its shape


print(newarr)
print(np.shape(newarr))

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

[[ 7 8]
[ 9 10]
[11 12]]]
(2, 3, 2)

In [72]: # 2 dimensional to 2 dimensional


import numpy as np

# Create a 2-D numpy array


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

# Print the original array and its shape


print("arr3:", arr3)
print("Shape is:", arr3.shape)

# Reshape the array to 2-D with shape (2, 4)


arr4 = arr3.reshape(2, 4)

# Print the new array and its shape


print("New arr4 is:", arr4)
print("New shape is:", arr4.shape)

arr3: [[1 2]
[3 4]
[5 6]
[7 8]]
Shape is: (4, 2)
New arr4 is: [[1 2 3 4]
[5 6 7 8]]
New shape is: (2, 4)

In [71]:
# 2 dimensional to 3 dimensional
import numpy as np
# Create a 2-D numpy array
arr3 = np.array([
[1, 2],
[3, 4],
[5, 6],
[7, 8]
])

# Print the original array and its shape


print("arr3:", arr3)
print("Shape is:", arr3.shape)

# Reshape the array to 3-D with shape (2, 2, 2)


arr4 = arr3.reshape(2, 2, 2)

# Print the new array and its shape


print("New arr4 is:", arr4)
print("New shape is:", arr4.shape)

arr3: [[1 2]
[3 4]
[5 6]
[7 8]]
Shape is: (4, 2)
New arr4 is: [[[1 2]
[3 4]]

[[5 6]
[7 8]]]
New shape is: (2, 2, 2)

In [70]:
# 3 DIMENSIONAL TO 2 DIMENSIONAL
import numpy as np

# Create a 3-D numpy array


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

# Print the original array and its shape


print("arr3:", arr3)
print("Shape is:", arr3.shape)

# Reshape the array to 2-D with shape (4, 2)


arr4 = arr3.reshape(4, 2)

# Print the new array and its shape


print("New arr4 is:", arr4)
print("New shape is:", arr4.shape)

arr3: [[[1 2]
[3 4]]

[[5 6]
[7 8]]]
Shape is: (2, 2, 2)
New arr4 is: [[1 2]
[3 4]
[5 6]
[7 8]]
New shape is: (4, 2)

Flattening the arrays Flattening array means converting a multidimensional array into a 1D array.

We can use reshape(-1) to do this.

In [69]: # 3 DIMENSIONAL INTO 1 DIMENSIONAL


import numpy as np

# Create a 3-D numpy array


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

# Print the original array and its shape


print("arr3:", arr3)
print("Shape is:", arr3.shape)

# Reshape the array to 1-D


arr4 = arr3.reshape(-1)

# Print the new array and its shape


print("New arr4 is:", arr4)
print("New shape is:", arr4.shape)

arr3: [[[1 2]
[3 4]]

[[5 6]
[7 8]]]
Shape is: (2, 2, 2)
New arr4 is: [1 2 3 4 5 6 7 8]
New shape is: (8,)

In [68]:
# 2 DIMENSIONAL TO 1 DIMENSIONAL
import numpy as np

# Create a 2-D numpy array


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

# Print the original array and its shape


print("arr3:", arr3)
print("Shape is:", arr3.shape)

# Reshape the array to 1-D


arr4 = arr3.reshape(-1)

# Print the new array and its shape


print("New arr4 is:", arr4)
print("New shape is:", arr4.shape)

arr3: [[1 2]
[3 4]
[5 6]
[7 8]]
Shape is: (4, 2)
New arr4 is: [1 2 3 4 5 6 7 8]
New shape is: (8,)

In [67]: import numpy as np

# Create a 2-D numpy array


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

# Flatten the array


flat_arr = arr.flatten()

# Print the original array


print("Original array:\n", arr)

# Print the flattened array


print("Flattened array:\n", flat_arr)

Original array:
[[1 2 3]
[4 5 6]]
Flattened array:
[1 2 3 4 5 6]

Can We Reshape Into any Shape?: Yes, as long as the elements required for reshaping are equal in
both shapes.

We can reshape an 8 elements 1D array into 4 elements in 2 rows 2D array but we cannot reshape it
into a 3 elements 3 rows 2D array as that would require 3x3 = 9 elements.

Example Try converting 1D array with 8 elements to a 2D array with 3 elements in each dimension (will
raise an error):

Returns Copy or View? Example Check if the returned array is a copy or a view:

In [ ]: import numpy as np

# Create a 1-D numpy array


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

# Attempt to reshape the array to 3 dimensions with shape (3, 3)


try:
newarr = arr.reshape(3, 3)
print(newarr)
except ValueError as e:
print("Error:", e)

Error: cannot reshape array of size 8 into shape (3,3)


In [65]:
import numpy as np

# Create a 1-D numpy array


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

# Reshape the array to 2 dimensions with shape (2, 4)


reshaped_arr = arr.reshape(2, 4)

# Print the base array of the reshaped array


print(reshaped_arr.base)

[1 2 3 4 5 6 7 8]

The example above returns the original array, so it is a view.

Unknown Dimension
You are allowed to have one "unknown" dimension.

Meaning that you do not have to specify an exact number for one of the dimensions in the reshape
method.

Pass -1 as the value, and NumPy will calculate this number for you.

Example Convert 1D array with 8 elements to 3D array with 2x2 elements:

In [64]:
import numpy as np

# Create a 1-D numpy array


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

# Reshape the array to 3 dimensions with shape (2, 2, 2)


newarr = arr.reshape(2, 2, -1)

# Print the reshaped array


print(newarr)

[[[1 2]
[3 4]]

[[5 6]
[7 8]]]

In [63]:
import numpy as np

# Create a 1-D numpy array


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

# Reshape the array to 3 dimensions with shape (3, 2, 2)


newarr = arr.reshape(3, 2, -1)

# Print the reshaped array


print(newarr)
[[[ 1 2]
[ 3 4]]

[[ 5 6]
[ 7 8]]

[[ 9 10]
[11 12]]]

Note: We can not pass -1 to more than one dimension

Note: There are a lot of functions for changing the shapes of arrays in numpy flatten, ravel and also for
rearranging the elements rot90, flip, fliplr, flipud etc. These fall under Intermediate to Advanced section
of numpy.

NumPy Array Iterating

Iterating Arrays Iterating means going through elements one by one.

As we deal with multi-dimensional arrays in numpy, we can do this using basic for loop of python.

If we iterate on a 1-D array it will go through each element one by one.

In [62]: # Example
# Iterate on the elements of the following 1-D array:
import numpy as np

# Create a 1-D numpy array


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

# Iterate through each element in the 1-D array


for x in arr:
print(x)

1
2
3

Iterating 2-D Arrays In a 2-D array it will go through all the rows.

In [61]:
# Example
# Iterate on the elements of the following 2-D array:
import numpy as np

# Create a 2-D numpy array


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

# Iterate through each row in the 2-D array


for x in arr:
print(x)

[1 2 3]
[4 5 6]
In [60]:
# Example
# Iterate on each scalar element of the 2-D array:
import numpy as np

# Create a 2-D numpy array


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

# Iterate through each element in the 2-D array


for x in arr:
for y in x:
print(y)

1
2
3
4
5
6

Iterating 3-D Arrays In a 3-D array it will go through all the 2-D arrays.

In [53]:
# Example
# Iterate on the elements of the following 3-D array:
import numpy as np

# Create a 3-D numpy array


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

# Iterate through each 2-D array in the 3-D array


for x in arr:
print(x)

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

In [52]:
import numpy as np

# Create a 3-D numpy array


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

# Iterate through each element in the 3-D array


for x in arr:
for y in x:
for z in y:
print(z)

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

Iterating Arrays Using nditer()


The function nditer() is a helping function that can be used from very basic to very advanced iterations.
It solves some basic issues which we face in iteration, lets go through it with examples.

Iterating on Each Scalar Element In basic for loops, iterating through each scalar of an array we need
to use n for loops which can be difficult to write for arrays with very high dimensionality.

In [54]: # Example
# Iterate through the following 3-D array:
import numpy as np

# Create a 3-D numpy array


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

# Iterate through each element in the 3-D array using np.nditer


for x in np.nditer(arr):
print(x)

1
2
3
4
5
6
7
8

Iterating Array With Different Data Types:

We can use op_dtypes argument and pass it the expected datatype to change the datatype of
elements while iterating.

NumPy does not change the data type of the element in-place (where the element is in array) so it
needs some other space to perform this action, that extra space is called buffer, and in order to enable
it in nditer() we pass flags=['buffered'].

In [55]:
# Example
# Iterate through the array as a string:
import numpy as np

# Create a numpy array


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

# Iterate through each element in the array as a string using np.nditer


for x in np.nditer(arr, flags=['buffered'], op_dtypes=['S']):
print(x)

np.bytes_(b'1')
np.bytes_(b'2')
np.bytes_(b'3')
Iterating With Different Step Size We can use filtering and followed by iteration.

In [56]: # Example
# Iterate through every scalar element of the 2D array skipping 1 element:
import numpy as np

# Create a 2D numpy array


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

# Iterate through every scalar element of the 2D array, skipping 1 element


for x in np.nditer(arr[:, ::2]):
print(x)

1
3
5
7

Enumerated Iteration Using ndenumerate(): Enumeration means mentioning sequence number of


somethings one by one.

Sometimes we require corresponding index of the element while iterating, the ndenumerate() method
can be used for those usecases.

In [57]:
# Example
# Enumerate on following 1D array elements:
import numpy as np

# Create a 1D numpy array


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

# Enumerate through each element in the array using np.ndenumerate


for idx, x in np.ndenumerate(arr):
print(idx, x)

(0,) 1
(1,) 2
(2,) 3

In [58]: # Example
# Enumerate on following 2D array's elements:
import numpy as np

# Create a 2D numpy array


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

# Enumerate through each element in the array using np.ndenumerate


for idx, x in np.ndenumerate(arr):
print(idx, x)

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

NumPy Joining Array

Joining NumPy Arrays Joining means putting contents of two or more arrays in a single array.

In SQL we join tables based on a key, whereas in NumPy we join arrays by axes.

We pass a sequence of arrays that we want to join to the concatenate() function, along with the axis. If
axis is not explicitly passed, it is taken as 0.

In [59]: # Example
# Join two arrays

import numpy as np

# Create the first numpy array


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

# Create the second numpy array


arr2 = np.array([4, 5, 6])

# Concatenate the arrays


arr = np.concatenate((arr1, arr2))

# Print the concatenated array


print(arr)

[1 2 3 4 5 6]

In [51]:
# Example
# Join two 2-D arrays along rows (axis=1):
import numpy as np

# Create two 2-D numpy arrays


arr1 = np.array([[1, 2], [3, 4]])
arr2 = np.array([[5, 6], [7, 8]])

# Concatenate the arrays along rows (axis=1)


arr = np.concatenate((arr1, arr2), axis=1)

# Print the concatenated array


print(arr)

# Create a new 1-D numpy array


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

[[1 2 5 6]
[3 4 7 8]]
Joining Arrays Using Stack Functions Stacking is same as concatenation, the only difference is that
stacking is done along a new axis.

We can concatenate two 1-D arrays along the second axis which would result in putting them one over
the other, ie. stacking.

We pass a sequence of arrays that we want to join to the stack() method along with the axis. If axis is
not explicitly passed it is taken as 0.

In [50]:
# Example
import numpy as np

# Create two numpy arrays


arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# Stack the arrays along the second axis (column-wise)


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

# Print the stacked array


print(arr)

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

Stacking Along Rows NumPy provides a helper function: hstack() to stack along rows.

In [49]:
# Example
import numpy as np

# Create two numpy arrays


arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# Stack the arrays horizontally (column-wise)


arr = np.hstack((arr1, arr2))

# Print the stacked array


print(arr)

[1 2 3 4 5 6]

Stacking Along Columns NumPy provides a helper function: vstack() to stack along columns.

In [48]:
# Example
import numpy as np

# Create two numpy arrays


arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# Stack the arrays vertically (row-wise)


arr = np.vstack((arr1, arr2))

# Print the stacked array


print(arr)

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

Stacking Along Height (depth) NumPy provides a helper function: dstack() to stack along height,
which is the same as depth.

In [47]: # Example
import numpy as np

# Create two numpy arrays


arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# Stack the arrays along the third axis (depth)


arr = np.dstack((arr1, arr2))

# Print the stacked array


print(arr)

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

NumPy Splitting Array

Splitting NumPy Arrays Splitting is reverse operation of Joining.

Joining merges multiple arrays into one and Splitting breaks one array into multiple.

We use array_split() for splitting arrays, we pass it the array we want to split and the number of splits.

In [46]:
# Example
# Split the array in 3 parts:

import numpy as np

# Create a numpy array


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

# Split the array into three parts


newarr = np.array_split(arr, 3)

# Print the new arrays


print(newarr)

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


Note: The return value is a list containing three arrays.

If the array has less elements than required, it will adjust from the end accordingly.

In [45]:
# Example
# Split the array in 4 parts:

import numpy as np

# Create a numpy array


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

# Split the array into four parts


newarr = np.array_split(arr, 4)

# Print the new arrays


print(newarr)

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

Note: We also have the method split() available but it will not adjust the elements when elements are
less in source array for splitting like in example above, array_split() worked properly but split() would
fail.

Split Into Arrays The return value of the array_split() method is an array containing each of the split as
an array.

If you split an array into 3 arrays, you can access them from the result just like any array element:

In [44]:
# Example
# Access the splitted arrays:

import numpy as np

# Create a numpy array


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

# Split the array into three arrays


newarr = np.array_split(arr, 3)

# Print each of the splitted arrays


print(newarr[0])
print(newarr[1])
print(newarr[2])

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

Splitting 2-D Arrays Use the same syntax when splitting 2-D arrays.

Use the array_split() method, pass in the array you want to split and the number of splits you want to
do.
In [43]:
# Example
# Split the 2-D array into three 2-D arrays.

import numpy as np

# Create a 2-D numpy array


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

# Split the array into three 2-D arrays


newarr = np.array_split(arr, 3)

# Print the new arrays


print(newarr)

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

The example above returns three 2-D arrays.

Let's look at another example, this time each element in the 2-D arrays contains 3 elements.

In [42]:
# Example
# Split the 2-D array into three 2-D arrays.

import numpy as np

# Create a 2-D numpy array


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

# Split the array into three 2-D arrays


newarr = np.array_split(arr, 3)

# Print the new arrays


print(newarr)

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

The example above returns three 2-D arrays.

In addition, you can specify which axis you want to do the split around.

The example below also returns three 2-D arrays, but they are split along the row (axis=1).

In [41]:
# Example
# Split the 2-D array into three 2-D arrays along rows.

import numpy as np

# Create a 2-D numpy array


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

# Split the array into three 2-D arrays along rows


newarr = np.array_split(arr, 3, axis=1)

# Print the new arrays


print(newarr)

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

An alternate solution is using hsplit() opposite of hstack()

In [40]: # Example
# Use the hsplit() method to split the 2-D array into three 2-D arrays alon

import numpy as np

# Create a 2-D numpy array


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

# Split the array into three 2-D arrays along rows


newarr = np.hsplit(arr, 3)

# Print the new arrays


print(newarr)

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

Note: Similar alternates to vstack() and dstack() are available as vsplit() and dsplit()
NumPy Searching Arrays

Searching Arrays You can search an array for a certain value, and return the indexes that get a match.

To search an array, use the where() method.

In [39]:
# Example
# Find the indexes where the value is 4:

import numpy as np

# Create a numpy array


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

# Find the indexes where the value is 4


x = np.where(arr == 4)

# Print the indexes


print(x)

(array([3, 5, 6]),)

The example above will return a tuple: (array([3, 5, 6],)

Which means that the value 4 is present at index 3, 5, and 6.

In [38]:
# Example
# Find the indexes where the values are even:

import numpy as np

# Create a numpy array


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

# Find the indexes where the values are even


x = np.where(arr % 2 == 0)

# Print the indexes


print(x)

(array([1, 3, 5, 7]),)

In [37]: # Example
# Find the indexes where the values are odd:

import numpy as np

# Create a numpy array


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

# Find the indexes where the values are odd


x = np.where(arr % 2 == 1)

# Print the indexes


print(x)

(array([0, 2, 4, 6]),)

Search Sorted There is a method called searchsorted() which performs a binary search in the array,
and returns the index where the specified value would be inserted to maintain the search order.

The searchsorted() method is assumed to be used on sorted arrays.

In [36]:
# Example
# Find the indexes where the value 7 should be inserted:

import numpy as np

# Create a numpy array


arr = np.array([6, 7, 8, 9])

# Find the index where the value 7 should be inserted


x = np.searchsorted(arr, 7)

# Print the index


print(x)

Example explained: The number 7 should be inserted on index 1 to remain the sort order.

The method starts the search from the left and returns the first index where the number 7 is no longer
larger than the next value.

Search From the Right Side By default the left most index is returned, but we can give side='right' to
return the right most index instead.

In [35]:
# Example
# Find the indexes where the value 7 should be inserted, starting from the

import numpy as np

# Create a numpy array


arr = np.array([6, 7, 8, 9])

# Find the index where the value 7 should be inserted, starting from the ri
x = np.searchsorted(arr, 7, side='right')

# Print the index


print(x)

Example explained: The number 7 should be inserted on index 2 to remain the sort order.
The method starts the search from the right and returns the first index where the number 7 is no longer
less than the next value.

Multiple Values To search for more than one value, use an array with the specified values.

In [34]:
# Example
# Find the indexes where the values 2, 4, and 6 should be inserted:

import numpy as np

# Create a numpy array


arr = np.array([1, 3, 5, 7])

# Find the indexes where the values 2, 4, and 6 should be inserted


x = np.searchsorted(arr, [2, 4, 6])

# Print the indexes


print(x)

[1 2 3]

The return value is an array: [1 2 3] containing the three indexes where 2, 4, 6 would be inserted in the
original array to maintain the order.

NumPy Sorting Arrays

Sorting Arrays Sorting means putting elements in an ordered sequence.

Ordered sequence is any sequence that has an order corresponding to elements, like numeric or
alphabetical, ascending or descending.

The NumPy ndarray object has a function called sort(), that will sort a specified array.

In [33]:
# Example
# Sort the array:

import numpy as np

# Create a numpy array


arr = np.array([3, 2, 0, 1])

# Sort the array


sorted_arr = np.sort(arr)

# Print the sorted array


print(sorted_arr)

[0 1 2 3]

Note: This method returns a copy of the array, leaving the original array unchanged.
You can also sort arrays of strings, or any other data type:

In [32]: # Example
# Sort the array alphabetically:

import numpy as np

# Create a numpy array of strings


arr = np.array(['banana', 'cherry', 'apple'])

# Sort the array alphabetically


sorted_arr = np.sort(arr)

# Print the sorted array


print(sorted_arr)

['apple' 'banana' 'cherry']

In [31]:
# Example
# Sort a boolean array:

import numpy as np

# Create a boolean numpy array


arr = np.array([True, False, True])

# Sort the array


sorted_arr = np.sort(arr)

# Print the sorted array


print(sorted_arr)

[False True True]

Sorting a 2-D Array If you use the sort() method on a 2-D array, both arrays will be sorted:

In [30]:
# Example
# Sort a 2-D array:

import numpy as np

# Create a 2-D numpy array


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

# Sort the array


sorted_arr = np.sort(arr)

# Print the sorted array


print(sorted_arr)
[[2 3 4]
[0 1 5]]

NumPy Filter Array

Filtering Arrays Getting some elements out of an existing array and creating a new array out of them is
called filtering.

In NumPy, you filter an array using a boolean index list.

A boolean index list is a list of booleans corresponding to indexes in the array.

If the value at an index is True that element is contained in the filtered array, if the value at that index is
False that element is excluded from the filtered array.

In [29]:
# Example
# Create an array from the elements on index 0 and 2:

import numpy as np

# Create a numpy array


arr = np.array([41, 42, 43, 44])

# Create a boolean index array


x = [True, False, True, False]

# Apply the boolean index array to the original array


newarr = arr[x]

# Print the new array with elements on index 0 and 2


print(newarr)

[41 43]

The example above will return [41, 43], why?

Because the new array contains only the values where the filter array had the value True, in this case,
index 0 and 2.

Creating the Filter Array In the example above we hard-coded the True and False values, but the
common use is to create a filter array based on conditions.

In [99]:
#Example
#Create a filter array that will return only values higher than 42:

import numpy as np

arr = np.array([41, 42, 43, 44])

# Create an empty list


filter_arr = []

# go through each element in arr


for element in arr:
# if the element is higher than 42, set the value to True, otherwise Fals
if element > 42:
filter_arr.append(True)
else:
filter_arr.append(False)

newarr = arr[filter_arr]

print(filter_arr)
print(newarr)

[False, False, True, True]


[43 44]

In [100]:
#Example
#Create a filter array that will return only even elements from the origina

import numpy as np

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

# Create an empty list


filter_arr = []

# go through each element in arr


for element in arr:
# if the element is completely divisble by 2, set the value to True, othe
if element % 2 == 0:
filter_arr.append(True)
else:
filter_arr.append(False)

newarr = arr[filter_arr]

print(filter_arr)
print(newarr)

[False, True, False, True, False, True, False]


[2 4 6]

Creating Filter Directly From Array The above example is quite a common task in NumPy and NumPy
provides a nice way to tackle it.

We can directly substitute the array instead of the iterable variable in our condition and it will work just
as we expect it to.

In [28]: # Example
# Create a filter array that will return only values higher than 42:

import numpy as np

# Create a numpy array


arr = np.array([41, 42, 43, 44])
# Create a filter array that will return only values higher than 42
filter_arr = arr > 42

# Apply the filter to the original array


newarr = arr[filter_arr]

# Print the filter array


print(filter_arr)

# Print the new array with values higher than 42


print(newarr)

[False False True True]


[43 44]

In [27]: # Example
# Create a filter array that will return only even elements from the origin

import numpy as np

# Create a numpy array


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

# Create a filter array that will return only even elements


filter_arr = arr % 2 == 0

# Apply the filter to the original array


newarr = arr[filter_arr]

# Print the filter array


print(filter_arr)

# Print the new array with only even elements


print(newarr)

[False True False True False True False]


[2 4 6]

In [1]:
import numpy as np

# Create two NumPy arrays


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

# Perform element-wise addition


result_addition = array1 + array2

# Display the original arrays and the results


print("Array 1:", array1)
print("Array 2:", array2)
print("Element-wise Addition:", result_addition)
Array 1: [1 2 3]
Array 2: [4 5 6]
Element-wise Addition: [5 7 9]

NumPy Basic Operations


The Plethora of built-in arithmetic functions is provided in Python NumPy.

1. Operations on a single NumPy array We can use overloaded arithmetic operators to do element-
wise operations on the array to create a new array. In the case of +=, -=, *= operators, the existing array
is modified.

In [11]: # Python program to demonstrate


# basic operations on single array
import numpy as np

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

# add 1 to every element


print ("Adding 1 to every element:", a+1)

# subtract 3 from each element


print ("Subtracting 3 from each element:", a-3)

# multiply each element by 10


print ("Multiplying each element by 10:", a*10)

# square each element


print ("Squaring each element:", a**2)

# modify existing array


a *= 2
print ("Doubled each element of original array:", a)

# transpose of array
a = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]])

print ("\nOriginal array:\n", a)


print ("Transpose of array:\n", a.T)

Adding 1 to every element: [2 3 6 4]


Subtracting 3 from each element: [-2 -1 2 0]
Multiplying each element by 10: [10 20 50 30]
Squaring each element: [ 1 4 25 9]
Doubled each element of original array: [ 2 4 10 6]

Original array:
[[1 2 3]
[3 4 5]
[9 6 0]]
Transpose of array:
[[1 3 9]
[2 4 6]
[3 5 0]]

NumPy – Unary Operators Many unary operations are provided as a method of ndarray class. This
includes sum, min, max, etc. These functions can also be applied row-wise or column-wise by setting
an axis parameter.

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

NumPy – Binary Operators These operations apply to the array elementwise and a new array is
created. You can use all basic arithmetic operators like +, -, /, etc. In the case of +=, -=, = operators, the
existing array is modified.

In [13]: # Python program to demonstrate


# binary operators in Numpy
import numpy as np

a = np.array([[1, 2],
[3, 4]])
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]]

NumPy ufuncs NumPy provides familiar mathematical functions such as sin, cos, exp, etc. These
functions also operate elementwise on an array, producing an array as output.

Note: All the operations we did above using overloaded operators can be done using ufuncs like
np.add, np.subtract, np.multiply, np.divide, np.sum, etc.

In [14]:
# Python program to demonstrate
# universal functions in numpy
import numpy as np

# create an array of sine values


a = np.array([0, np.pi/2, np.pi])
print ("Sine values of array elements:", np.sin(a))

# exponential values
a = np.array([0, 1, 2, 3])
print ("Exponent of array elements:", np.exp(a))

# square root of array values


print ("Square root of array elements:", np.sqrt(a))

Sine values of array elements: [0.0000000e+00 1.0000000e+00 1.2246468e-16]


Exponent of array elements: [ 1. 2.71828183 7.3890561 20.08553692]
Square root of array elements: [0. 1. 1.41421356 1.73205081]

NumPy Sorting Arrays There is a simple np.sort() method for sorting Python NumPy arrays. Let’s
explore it a bit.

In [15]:
# Python program to demonstrate sorting in numpy
import numpy as np

a = np.array([[1, 4, 2],
[3, 4, 6],
[0, -1, 5]])

# sorted array
print ("Array elements in sorted order:\n",
np.sort(a, axis = None))

# sort array row-wise


print ("Row-wise sorted array:\n",
np.sort(a, axis = 1))
# specify sort algorithm
print ("Column wise sort by applying merge-sort:\n",
np.sort(a, axis = 0, kind = 'mergesort'))

# Example to show sorting of structured array


# set alias names for dtypes
dtypes = [('name', 'S10'), ('grad_year', int), ('cgpa', float)]

# Values to be put in array


values = [('Hrithik', 2009, 8.5), ('Ajay', 2008, 8.7),
('Pankaj', 2008, 7.9), ('Aakash', 2009, 9.0)]

# Creating array
arr = np.array(values, dtype = dtypes)
print ("\nArray sorted by names:\n",
np.sort(arr, order = 'name'))

print ("Array sorted by graduation year and then cgpa:\n",


np.sort(arr, order = ['grad_year', 'cgpa']))

Array elements in sorted order:


[-1 0 1 2 3 4 4 5 6]
Row-wise sorted array:
[[ 1 2 4]
[ 3 4 6]
[-1 0 5]]
Column wise sort by applying merge-sort:
[[ 0 -1 2]
[ 1 4 5]
[ 3 4 6]]

Array sorted by names:


[(b'Aakash', 2009, 9. ) (b'Ajay', 2008, 8.7) (b'Hrithik', 2009, 8.5)
(b'Pankaj', 2008, 7.9)]
Array sorted by graduation year and then cgpa:
[(b'Pankaj', 2008, 7.9) (b'Ajay', 2008, 8.7) (b'Hrithik', 2009, 8.5)
(b'Aakash', 2009, 9. )]

What are NumPy Commands?


NumPy commands refer to the functions and methods available in the NumPy library that operate on
arrays. Here are a few commonly used NumPy commands:

np.array(): Create an array. np.arange(): Return evenly spaced values within a given interval. np.zeros(),
np.ones(), np.full(): Create new arrays filled with zeros, ones, or a specified value, respectively. np.dot():
Dot product of two arrays. np.reshape(): Gives a new shape to an array without changing its data.
np.mean(), np.median(), np.std(): Compute the mean, median, and standard deviation of array
elements. np.linalg.inv(): Compute the (multiplicative) inverse of a matrix.

You might also like