



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
An introduction to NumPy, a powerful library for numerical computations in Python. It covers the basics of creating arrays, indexing and slicing, vector operations, and matrix operations using NumPy. The document also includes examples of creating arrays of different shapes and sizes, as well as various ways of indexing and slicing arrays. Additionally, it covers scalar operations, dot product, and functions applied to elements of arrays.
What you will learn
Typology: Study Guides, Projects, Research
1 / 5
This page cannot be seen from the preview
Don't miss anything!
Numpy Basics
In [1]: import numpy as np
#Create a rank 1 array a = np.array([1, 2, 3]) print(type(a))# check the object created print(a.dtype)# data type of the elements of the array print(a.ndim)# check the dimention of the array print(a.shape)# check the (row,col) of the array, shape returns a tuple print(a[0], a[1], a[2]) a[0] = 5 # Change an element of the array print(a)
b = np.array([[1,2,3],[4,5,6]]) print(b.shape) print(b[0, 0], b[0, 1], b[1, 0])
<class 'numpy.ndarray'> int 1 (3,) 1 2 3 [5 2 3] (2, 3) 1 2 4
In [2]: #different ways of creating arrays import numpy as np
a = np.zeros((2,2)) print(a)
b = np.ones((1,2))
print(b)
c = np.full((2,2), 7) print(c)
d = np.eye(2) print(d)
e = np.random.random((2,2)) print(e)
#using arange and reshape methods f = np.arange(12).reshape(4,3) print(f)
[[0. 0.] [0. 0.]] [[1. 1.]] [[7 7] [7 7]] [[1. 0.] [0. 1.]] [[0.85243703 0.07421425] [0.35034596 0.0979054 ]] [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]]
In [3]: #Indexing & Slicing import numpy as np a = np.arange(10) print(a) print(a[0])#prints the element at the given index
s = slice(0,7,2) # a part of array with starting index and ending index #with steps given is sliced print (a[s]) b = a[2:9:2]# another way of slicing print(b)
[0 1 2 3 4 5 6 7 8 9] 0 [0 2 4 6]
print(b*2)
#functions applied to elements of arrays print(a.sum()) print(a.min()) print(np.log(a)) print('\n') print(np.sqrt(b))
[ 4 13 17 11] [ 3 40 72 18] 133 [ 4 6 9 10]
In [6]: ar = np.array([[6, 1, 1], [4, -2, 5], [2, 8, 7]]) print(ar) print('\n') #transpose ar_trans= ar.T print(ar_trans) print('\n') #determinant print(np.linalg.det(ar)) #rank print(np.linalg.matrix_rank(ar)) #inverse print(np.linalg.inv(ar)) print('\n') #power iteration print(np.linalg.matrix_power(ar, 3))
[[ 6 1 1] [ 4 -2 5] [ 2 8 7]]