Numpy
Numpy
1 Numpy
Numpy is the core library for scientific computing in Python. It provides a high-performance
multidimensional array object, and tools for working with these arrays. If you are already familiar
with MATLAB, you might find this manual useful to get started with Numpy.
1.0.1 Arrays
What are NumPy Arrays? NumPy is a Python package that stands for ‘Numerical Python’. It is
the core library for scientific computing, which contains a powerful n-dimensional array object.
Where is NumPy used? Python NumPy arrays provide tools for integrating C, C++, etc. It is
also useful in linear algebra, random number capability etc. NumPy array can also be used as
an efficient multi-dimensional container for generic data. Now, let me tell you what exactly is a
Python NumPy array.
Python NumPy Array: Numpy array is a powerful N-dimensional array object which is in the
form of rows and columns. We can initialize NumPy arrays from nested Python lists and access it
elements. In order to perform these NumPy operations, the next question which will come in your
mind is:
[1]: import numpy as np
# Prints "(3,)"
print(a.shape)
1
print(a)
<class 'numpy.ndarray'>
(3,)
1 2 3
[5 2 3]
Why NumPy is used in Python? We use python NumPy array instead of a list because of
the below three reasons:
Less Memory Fast Convenient
The very first reason to choose python NumPy array is that it occupies less memory as compared
to list. Then, it is pretty fast in terms of execution and at the same time, it is very convenient
to work with NumPy. So these are the major advantages that Python NumPy array has over list.
Consider the below example:
[2]: import numpy as np
import sys
S = range(1000)
print(sys.getsizeof(S) * len(S))
D = np.arange(1000)
print(D.size * D.itemsize)
48000
4000
48000 4000
The above output shows that the memory allocated by list (denoted by S) is 48000 whereas the
memory allocated by the NumPy array is just 4000. From this, you can conclude that there is a
major difference between the two and this makes Python NumPy array as the preferred choice over
list.
[3]: import numpy as np
(2, 3)
1 2 4
2
[4]: import numpy as np
[[0. 0.]
[0. 0.]]
[[1. 1.]]
[[7 7]
[7 7]]
[[1. 0.]
[0. 1.]]
[[0.61351729 0.71237344]
[0.3913626 0.41718071]]
3
# [[ 1 2 3 4]
# [ 5 6 7 8]
# [ 9 10 11 12]]
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
# Use slicing to pull out the subarray consisting of the first 2 rows
# and columns 1 and 2; b is the following array of shape (2, 2):
# [[2 3]
# [6 7]]
b = a[:2, 1:3]
print(b)
[[2 3]
[6 7]]
2
77
You can also mix integer indexing with slice indexing. However, doing so will yield an array of
lower rank than the original array. Note that this is quite different from the way that MATLAB
handles array slicing:
[6]: import numpy as np
# Two ways of accessing the data in the middle row of the array.
# Mixing integer indexing with slices yields an array of lower rank,
# while using only slices yields an array of the same rank as the
# original array:
row1 = a[1, :] # Rank 1 view of the second row of a
row2 = a[1:2, :] # Rank 2 view of the second row of a
print(row1, row1.shape) # Prints "[5 6 7 8] (4,)"
print(row2, row2.shape) # Prints "[[5 6 7 8]] (1, 4)"
4
col2 = a[:, 1:2]
print(col1, col1.shape) # Prints "[ 2 6 10] (3,)"
print(col2, col2.shape) # Prints "[[ 2]
#[ 6]
#[10]] (3, 1)"
[5 6 7 8] (4,)
[[5 6 7 8]] (1, 4)
We can make the same distinction when accessing columns of an array
[ 2 6 10] (3,)
[[ 2]
[ 6]
[10]] (3, 1)
Integer array indexing: When you index into numpy arrays using slicing, the resulting array view
will always be a subarray of the original array. In contrast, integer array indexing allows you to
construct arbitrary arrays using the data from another array. Here is an example:
[7]: import numpy as np
# indexing
print("indexing")
# An example of integer array indexing.
# The returned array will have shape (3,)
print(a[[0, 1, 2], [0, 1, 0]])
# When using integer array indexing, you can reuse the same
# element from the source array:
print(a[[0, 0], [1, 1]]) # Prints "[2 2]"
[[1 2]
[3 4]
[5 6]]
(3, 2)
indexing
[1 4 5]
[2 2]
[2 2]
5
[8]: import numpy as np
# An example of matrix
print(a)
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
[0 2 0 1]
Create an array of indices
Select one element from each row of a using the indices in b
[ 1 6 7 11]
Mutate one element from each row of a using the indices in b
[[11 2 3]
[ 4 5 16]
[17 8 9]
[10 21 12]]
1.0.3 Datatypes
Every numpy array is a grid of elements of the same type. Numpy provides a large set of numeric
datatypes that you can use to construct arrays. Numpy tries to guess a datatype when you create
an array, but functions that construct arrays usually also include an optional argument to explicitly
specify the datatype. Here is an example:
6
[9]: import numpy as np
int32
float64
int64
# creating array
arr = np.array([2, 4, 6, 8, 10])
# assigning arr to nc
nc = arr
# updating nc
nc[0] = 12
id of arr 3151592156496
id of nc 3151592156496
original array: [12 4 6 8 10]
assigned array: [12 4 6 8 10]
7
[11]: import numpy as np
# creating array
arr = np.array([2, 4, 6, 8, 10])
# creating view
v = arr.view()
id of arr 3151592156208
id of v 3151592180784
original array: [12 4 6 8 10]
view: [12 4 6 8 10]
for x in arr:
print(x)
1
2
3
import numpy as np
8
for x in arr:
print(x)
[1 2 3]
[4 5 6]
import numpy as np
for x in arr:
for y in x:
print(y)
1
2
3
4
5
6
for x in np.nditer(arr):
print(x, end=' ')
1 2 3 4 5 6 7 8
1.0.6 Reshape
[16]: # Convert the following 1-D array with 12 elements into a 2-D array.
import numpy as np
newarr = arr.reshape(4, 3)
print(newarr)
[[ 1 2 3]
9
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
[17]: # 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:
import numpy as np
newarr = arr.reshape(2, 3, 2)
print(newarr)
[[[ 1 2]
[ 3 4]
[ 5 6]]
[[ 7 8]
[ 9 10]
[11 12]]]
import numpy as np
newarr = arr.reshape(-1)
print(newarr)
[1 2 3 4 5 6]
10
[19]: import numpy as np
print(arr)
[1 2 3 4 5 6]
import numpy as np
print(arr)
[[1 2 5 6]
[3 4 7 8]]
import numpy as np
newarr = np.array_split(arr, 3)
print(newarr)
print(type(newarr))
print(newarr[0])
print(newarr[1])
print(newarr[2])
11
[array([1, 2]), array([3, 4]), array([5, 6])]
<class 'list'>
[1 2]
[3 4]
[5 6]
import numpy as np
arr = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]])
newarr = np.array_split(arr, 3)
print(newarr)
print(type(newarr))
print(newarr[0])
print(newarr[1])
print(newarr[2])
[array([[1, 2],
[3, 4]]), array([[5, 6],
[7, 8]]), array([[ 9, 10],
[11, 12]])]
<class 'list'>
[[1 2]
[3 4]]
[[5 6]
[7 8]]
[[ 9 10]
[11 12]]
import numpy as np
x = np.where(arr == 4)
print(x)
12
# 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.
x = np.where(arr % 2 == 0)
print(x)
import numpy as np
print(np.sort(arr))
[0 1 2 3]
[26]: # You can also sort arrays of strings, or any other data type:
# Sort the array alphabetically:
import numpy as np
print(np.sort(arr))
import numpy as np
13
arr = np.array([[3, 2, 4], [5, 0, 1]])
print(np.sort(arr))
[[2 3 4]
[0 1 5]]
1.0.11 Exercise
01. Create an array of table 02 unig Numpy Array and then Iterate it.
02. Create 8-by-8 matrix and fill it with a pattern of checkerboard like
# 0 1 0
# 1 0 1
# 0 1 0
03. Create 10-by-10 matrix, in which the elements on the borders will be equal to 1, and inside 0.
04. Create a given matrix first then find the number of rows and columns.
# [[10 11 12 13]
# [14 15 16 17]
# [18 19 20 21]]
05. Reshape above 2-D array to one dimensional array
06. Create a 5-by-7 matrix filled with values from 55 to 90
14