Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Num Py

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

What is NumPy?

NumPy stands for 'Numerical Python'. It is a Python library used for working with arrays. It is a library consisting of multidimensional array objects.

It is useful in linear algebra, random number capability etc. NumPy array can also be used as an efficient multi-dimensional container for generic
data.

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.

Installation of NumPy
!pip install numpy

In [2]: 1 import numpy as np

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 [2]: 1 arr = np.array([1, 2, 3, 4, 5])
2 print(arr)
3 print(type(arr))

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

type(): This built-in Python function tells us the type of the object passed to it. Like in above code it shows that arr is numpy.ndarray type.

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

In [4]: 1 #Use a tuple to create a NumPy array:


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

[1 2 3 4 5]

Dimensions in Arrays
A dimension in arrays is one level of array depth (nested arrays). nested array: are arrays that have arrays as their elements.

0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.

In [7]: 1 # Example
2 ​
3 arr = np.array(42)
4 print(arr)

42

1-D Arrays
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array. These are the most common and basic arrays.

In [10]: 1 # Example
2 ​
3 arr = np.array([1, 2, 3, 4, 5])
4 print(arr)
5 ​

[1 2 3 4 5]

2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.

These are often used to represent matrix or 2nd order tensors.

In [12]: 1 # Example
2 ​
3 arr = np.array([[1, 2, 3], [4, 5, 6]])
4 print(arr)
5 ​

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

3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array. These are often used to represent a 3rd order tensor.
In [13]: 1 # Example
2 ​
3 arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
4 print(arr)
5 ​

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

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

Check Number of Dimensions?


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

In [14]: 1 # Example
2 ​
3 a = np.array(42)
4 b = np.array([1, 2, 3, 4, 5])
5 c = np.array([[1, 2, 3], [4, 5, 6]])
6 d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
7 ​
8 print(a.ndim)
9 print(b.ndim)
10 print(c.ndim)
11 print(d.ndim)
12 ​

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.

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


2 ​
3 print(arr)
4 print('number of dimensions :', arr.ndim)

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

In this array the innermost dimension (5th dimension) has 4 elements,

the 4th dimension has 1 element that is the vector,

the 3rd dimension has 1 element that is the matrix,

the 2nd dimension has 1 element that is 3D array

and 1st dimension has 1 element that is a 4D array.

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.

Access 1-D Arrays:


In [23]: 1 # Example
2 #Get the first element from the following array:
3 ​
4 arr = np.array([1, 2, 3, 4])
5 print(arr[0])

In [24]: 1 print(arr[2] + arr[3])

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.

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


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

2nd element on 1st row: 2

In [21]: 1 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.

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

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

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


2 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.

In [27]: 1 #Example
2 arr = np.array([1, 2, 3, 4, 5, 6, 7])
3 print(arr[1:5])

[2 3 4 5]

In [28]: 1 # Slice elements from index 4 to the end of the array:


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

[5 6 7]

Negative Slicing
Use the minus operator to refer to an index from the end:
In [29]: 1 #Example
2 #Slice from the index 3 from the end to index 1 from the end: import numpy as np
3 arr = np.array([1, 2, 3, 4, 5, 6, 7])
4 print(arr[-3:-1])
5 ​

[5 6]

Using Step size


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

In [31]: 1 # Example
2 arr = np.array([1, 2, 3, 4, 5, 6, 7])
3 print(arr[1:5:2])

[2 4]

In [5]: 1 # Return every other element from the entire array:


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

[1 3 5 7]

Slicing 2-D Arrays


In [33]: 1 # Example
2 # From the second element, slice elements from index 1 to index 4 (not included):
3 ​
4 arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
5 print(arr[1, 1:4])
6 ​

[7 8 9]

In [34]: 1 # From both elements, slice index 1 to index 4 (not included), this will return a 2-D array:
2 ​
3 arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
4 print(arr[0:2, 1:4])
5 ​

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

Data Types in NumPy


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

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 [36]: 1 #Example
2 #Get the data type of an array object: import numpy as np
3 arr = np.array([1, 2, 3, 4])
4 print(arr.dtype)

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.

In [41]: 1 arr = np.array([1.1, 2.1, 3.1])


2 newarr = arr.astype('i') # arr.astype(int)
3 print(newarr)
4 print(newarr.dtype)

[1 2 3]
int32

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


2 newarr = arr.astype(bool)
3 print(newarr)
4 print(newarr.dtype)

[ True False True]


bool

NumPy Array Shape


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

NumPy arrays have an attribute called shape that returns a tuple with each index having the number of corresponding elements.
In [43]: 1 #Example
2 ​
3 arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
4 print(arr.shape)

(2, 4)

In [45]: 1 arr = np.array([1, 1, 3, 4], ndmin=5)


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

[[[[[1 1 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 [46]: 1 arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
2 newarr = arr.reshape(4, 3)
3 print(newarr)
4 ​

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

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 [48]: 1 arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])


2 newarr = arr.reshape(2, 3, 2)
3 print(newarr)
4 ​

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

[[ 7 8]
[ 9 10]
[11 12]]]

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

newarr = arr.reshape(3, 3)

print(newarr)
Flattening the arrays
Flattening array means converting a multidimensional array into a 1D array. We can use reshape(-1) to do this.

Example

Convert the array into a 1D array:

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


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

[1 2 3 4 5 6]

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


2 for x in arr:
3 print(x)

1
2
3

Iterating 2-D Arrays


In a 2-D array it will go through all the rows.
In [52]: 1 arr = np.array([[1, 2, 3], [4, 5, 6]])
2 for x in arr:
3 print(x)

[1 2 3]
[4 5 6]

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


2 for x in arr:
3 for y in x:
4 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 [54]: 1 arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
2 ​
3 for x in arr:
4 print(x)

[[1 2 3]
[4 5 6]]
[[ 7 8 9]
[10 11 12]]
In [55]: 1 for x in arr:
2 for y in x:
3 for z in y:
4 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. Example
In [56]: 1 arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
2 for x in np.nditer(arr):
3 print(x)
4 ​

1
2
3
4
5
6
7
8

Iterating with Different Step Size


We can use filtering and followed by iteration.

Example

Iterate through every scalar element of the 2D array skipping 2 element:

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


2 for x in np.nditer(arr[:, ::3]): # change the coluns of last tuple
3 print(x)
4 ​

1
4
5
8

NumPy Joining Array


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

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


2 arr2 = np.array([4, 5, 6])
3 arr = np.concatenate((arr1, arr2))
4 print(arr)
5 ​

[1 2 3 4 5 6]

In [60]: 1 arr1 = np.array([[1, 2], [3, 4]])


2 arr2 = np.array([[5, 6], [7, 8]])
3 arr = np.concatenate((arr1, arr2), axis=1)
4 print(arr)
5 ​

[[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.

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


2 ​
3 arr2 = np.array([4, 5, 6])
4 ​
5 arr = np.stack((arr1, arr2), axis=1)
6 ​
7 print(arr)

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

Stacking Along Rows :


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

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


2 ​
3 arr2 = np.array([4, 5, 6])
4 ​
5 arr = np.hstack((arr1, arr2))
6 ​
7 print(arr)

[1 2 3 4 5 6]

Stacking Along Columns :


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

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


2 ​
3 arr2 = np.array([4, 5, 6])
4 ​
5 arr = np.vstack((arr1, arr2))
6 ​
7 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 [66]: 1 arr1 = np.array([1, 2, 3])
2 ​
3 arr2 = np.array([4, 5, 6])
4 ​
5 arr = np.dstack((arr1, arr2))
6 ​
7 print(arr)

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

NumPy Splitting Array


In [67]: 1 arr = np.array([1, 2, 3, 4, 5, 6])
2 newarr = np.array_split(arr, 3) # also try (np.array_split(arr, 4) )
3 print(newarr)

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

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


2 newarr = np.array_split(arr, 3)
3 print(newarr[0])
4 print(newarr[1])
5 print(newarr[2])

[1 2]
[3 4]
[5 6]
In [70]: 1 arr = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]])
2 newarr = np.array_split(arr, 3)
3 print(newarr)

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

In [72]: 1 arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]])
2 newarr = np.array_split(arr, 3, axis=1)
3 print(newarr)
4 ​

[array([[ 1],
[ 4],
[ 7],
[10],
[13],
[16]]), array([[ 2],
[ 5],
[ 8],
[11],
[14],
[17]]), array([[ 3],
[ 6],
[ 9],
[12],
[15],
[18]])]
In [73]: 1 arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]])
2 newarr = np.hsplit(arr, 3)
3 print(newarr)

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

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


2 x = np.where(arr == 4)
3 print(x)

(array([3, 5, 6], dtype=int64),)


In [76]: 1 arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
2 x = np.where(arr%2 == 0)
3 print(x)

(array([1, 3, 5, 7], dtype=int64),)

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 [77]: 1 arr = np.array([6, 7, 8, 9])


2 x = np.searchsorted(arr, 7)
3 print(x)

In [79]: 1 arr = np.array([6, 7, 8, 9])


2 x = np.searchsorted(arr, 7, side='right')
3 print(x)
4 ​

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


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

[1 2 3]

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 [82]: 1 arr = np.array([41, 42, 43, 44])


2 x = [True, False, True, False]
3 newarr = arr[x]
4 print(newarr)
5 ​

[41 43]

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 [87]: 1 arr = np.array([41, 42, 43, 44]) # Create an empty list


2 filter_arr = []
3 # go through each element in arr
4 for element in arr:
5 # if the element is higher than 42, set the value to True, otherwise False:
6 if element > 42:
7 filter_arr.append(True)
8 else:
9 filter_arr.append(False)
10
11 newarr = arr[filter_arr]
12 print(filter_arr)
13 print(newarr)
14 ​

[False, False, True, True]


[43 44]

Creating Filter Directly From Array


In [89]: 1 arr = np.array([41, 42, 43, 44])
2 filter_arr = arr > 42
3 newarr = arr[filter_arr]
4 print(filter_arr)
5 print(newarr)
6 ​

[False False True True]


[43 44]

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


2 filter_arr = arr % 2 == 0
3 newarr = arr[filter_arr]
4 ​
5 print(filter_arr)
6 print(newarr)
7 ​

[False True False True False True False]


[2 4 6]

Numpy Array Transpose


In [91]: 1 arr = np.array([[3, 2, 4], [5, 0, 1]])
2 print(np.transpose(arr))

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

Numpy Matrix
In [92]: 1 # make a matrix with numpy
2 ​
3 g = np.matrix('[1, 2, 3; 4, 0, 6; 7, 8, -9]')
4 ​
5 print(g)

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

In [93]: 1 # applying matrix.min() method


2 s = g.min()
3 print(s)

-9

Transpose of matrix :

In [5]: 1 A = np.matrix([[3, 2, 4], [5, 0, 1]])


2 print(np.transpose(A))

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

Inverse of matrix :
In [66]: 1 A = np.array([[6, 1, 1],
2 [4, -2, 5],
3 [2, 8, 7]])
4 print("\nInverse of A:\n", np.linalg.inv(A))

Inverse of A:
[[ 0.17647059 -0.00326797 -0.02287582]
[ 0.05882353 -0.13071895 0.08496732]
[-0.11764706 0.1503268 0.05228758]]

Trace of Matrix :

In [67]: 1 A = np.array([[6, 1, 1],


2 [4, -2, 5],
3 [2, 8, 7]])
4 print(A)
5 print("\nTrace of A:", np.trace(A))

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

Trace of A: 11

Determinant of matrix:
In [73]: 1 n_array = np.array([[50, 29], [30, 44]])
2 # Displaying the Matrix
3 print("Numpy Matrix is:", n_array)
4 ​
5 # calculating the determinant of matrix
6 det = np.linalg.det(n_array)
7 ​
8 print("\nDeterminant of given 2X2 matrix:", int(det))

Numpy Matrix is: [[50 29]


[30 44]]

Determinant of given 2X2 matrix: 1330

Addition of two matrix :

In [68]: 1 A = np.array([[1, 2], [3, 4]])


2 # creating second matrix
3 B = np.array([[4, 5], [6, 7]])
4 print("Printing elements of first matrix: ",A)
5 ​
6 print("Printing elements of second matrix: ",B)
7 # adding two matrix
8 print("Addition of two matrix")
9 print(np.add(A, B))

Printing elements of first matrix: [[1 2]


[3 4]]
Printing elements of second matrix: [[4 5]
[6 7]]
Addition of two matrix
[[ 5 7]
[ 9 11]]

Subtracting two matrix :


In [69]: 1 print("Subtraction of two matrix")
2 print(np.subtract(A, B))

Subtraction of two matrix


[[-3 -3]
[-3 -3]]

Matrix multiplication of 2 square matrices :

In [70]: 1 p = [[1, 2], [2, 3]]


2 q = [[4, 5], [6, 7]]
3 ​
4 print("Matrix p :", p)
5 ​
6 print("Matrix q :", q)
7 ​
8 # computing product
9 result = np.dot(p, q)
10 # printing the result
11 print("The matrix multiplication is :")
12 print(result)

Matrix p : [[1, 2], [2, 3]]


Matrix q : [[4, 5], [6, 7]]
The matrix multiplication is :
[[16 19]
[26 31]]

Matrix multiplication of 2 rectangular matrices:


In [71]: 1 p = [[1, 2], [2, 3], [4, 5]]
2 q = [[4, 5, 1], [6, 7, 2]]
3 print("Matrix p :", p)
4 ​
5 print("Matrix q :", q)
6 ​
7 # computing product
8 result = np.dot(p, q)
9 # printing the result
10 print("The matrix multiplication is :")
11 print(result)

Matrix p : [[1, 2], [2, 3], [4, 5]]


Matrix q : [[4, 5, 1], [6, 7, 2]]
The matrix multiplication is :
[[16 19 5]
[26 31 8]
[46 55 14]]

Get the eigen values of a matrix :

In [72]: 1 from numpy import linalg


2 # using np.eigvals() method
3 gfg = linalg.eigvals([[1, 2], [3, 4]])
4 print(gfg)

[-0.37228132 5.37228132]

Matrix multiplication of 2 rectangular matrices


In [71]: 1 p = [[1, 2], [2, 3], [4, 5]]
2 q = [[4, 5, 1], [6, 7, 2]]
3 print("Matrix p :", p)
4 ​
5 print("Matrix q :", q)
6 ​
7 # computing product
8 result = np.dot(p, q)
9 # printing the result
10 print("The matrix multiplication is :")
11 print(result)

Matrix p : [[1, 2], [2, 3], [4, 5]]


Matrix q : [[4, 5, 1], [6, 7, 2]]
The matrix multiplication is :
[[16 19 5]
[26 31 8]
[46 55 14]]

You might also like