Similar Notebooks
Copyright © Code Fetcher 2022
Hermina Petric Maretic, EPFL LTS4
NumPy is the fundamental package for scientific computing with Python. It contains among other things:
- a powerful N-dimensional array object
- sophisticated (broadcasting) functions
- tools for integrating C/C++ and Fortran code
- useful linear algebra, Fourier transform, and random number capabilities
Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data. Arbitrary data-types can be defined. This allows NumPy to seamlessly and speedily integrate with a wide variety of databases.
In [1]:
import numpy as np
In [2]:
#create a numpy array
a = np.array([1,2,3,4])
a
Out[2]:
In [3]:
#or a 2 dimensional array
m = np.array([[1,2],[3,4]])
m
Out[3]:
In [4]:
m[0,0]
Out[4]:
In [5]:
m[:,1]
Out[5]:
In [6]:
a[:2]
Out[6]:
In [7]:
a[-2] #second last element of the array
Out[7]:
In [8]:
a[-2:] #last two elements of the array
Out[8]:
In [9]:
b = [1,2,3,4]
In [10]:
b + b
b
Out[10]:
In [11]:
a + a
a
Out[11]:
In [12]:
#if you want to add elements to a
np.append(a,a)
Out[12]:
In [13]:
np.append(a,[1,2,3])
Out[13]:
In [14]:
np.insert(a, 1, 5) #insert 5 on position number 1
Out[14]:
In [15]:
a + 3
Out[15]:
In [16]:
a * 3
Out[16]:
In [17]:
a ** 3
Out[17]:
In [18]:
a * a
Out[18]:
In [19]:
a.sum()
Out[19]:
In [20]:
m * m #still elementwise multiplication
Out[20]:
In [21]:
np.dot(m,m) #standard matrix multiplication
Out[21]:
In [22]:
m = np.matrix(m) #there is a type matrix
m * m #for matrices, multiplication works as we're used to
Out[22]:
In [23]:
x = np.arange(0,10,2) #beginning, end, step
x
Out[23]:
In [24]:
np.linspace(0,10,5) #beginning, end, number of variables
Out[24]:
In [25]:
np.logspace(0,10,10,base=2) #beginning, end, number of variables
Out[25]:
In [26]:
np.diag([1,2,3])
Out[26]:
In [27]:
np.zeros(5)
Out[27]:
In [28]:
np.ones((3,3))
Out[28]:
In [29]:
np.random.rand(5,2)
Out[29]:
In [30]:
np.diag(m)
Out[30]:
In [31]:
np.trace(m)
Out[31]:
In [32]:
m.T
Out[32]:
In [33]:
m1 = np.linalg.inv(m)
m1
Out[33]:
In [34]:
np.linalg.det(m)
Out[34]:
In [35]:
np.linalg.det(m1)
Out[35]:
In [36]:
[eival, eivec] = np.linalg.eig(m)
In [37]:
eival
Out[37]:
In [38]:
eivec
Out[38]: