NumPy is the fundamental package for scientific computing with Python. It contains among other things:
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.
import numpy as np
#create a numpy array
a = np.array([1,2,3,4])
a
array([1, 2, 3, 4])
#or a 2 dimensional array
m = np.array([[1,2],[3,4]])
m
array([[1, 2], [3, 4]])
m[0,0]
1
m[:,1]
array([2, 4])
a[:2]
array([1, 2])
a[-2] #second last element of the array
3
a[-2:] #last two elements of the array
array([3, 4])
b = [1,2,3,4]
b + b
b
[1, 2, 3, 4]
a + a
a
array([1, 2, 3, 4])
#if you want to add elements to a
np.append(a,a)
array([1, 2, 3, 4, 1, 2, 3, 4])
np.append(a,[1,2,3])
array([1, 2, 3, 4, 1, 2, 3])
np.insert(a, 1, 5) #insert 5 on position number 1
array([1, 5, 2, 3, 4])
a + 3
array([4, 5, 6, 7])
a * 3
array([ 3, 6, 9, 12])
a ** 3
array([ 1, 8, 27, 64])
a * a
array([ 1, 4, 9, 16])
a.sum()
10
m * m #still elementwise multiplication
array([[ 1, 4], [ 9, 16]])
np.dot(m,m) #standard matrix multiplication
array([[ 7, 10], [15, 22]])
m = np.matrix(m) #there is a type matrix
m * m #for matrices, multiplication works as we're used to
matrix([[ 7, 10], [15, 22]])
x = np.arange(0,10,2) #beginning, end, step
x
array([0, 2, 4, 6, 8])
np.linspace(0,10,5) #beginning, end, number of variables
array([ 0. , 2.5, 5. , 7.5, 10. ])
np.logspace(0,10,10,base=2) #beginning, end, number of variables
array([ 1.00000000e+00, 2.16011948e+00, 4.66611616e+00, 1.00793684e+01, 2.17726400e+01, 4.70315038e+01, 1.01593667e+02, 2.19454460e+02, 4.74047853e+02, 1.02400000e+03])
np.diag([1,2,3])
array([[1, 0, 0], [0, 2, 0], [0, 0, 3]])
np.zeros(5)
array([ 0., 0., 0., 0., 0.])
np.ones((3,3))
array([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]])
np.random.rand(5,2)
array([[ 0.95867801, 0.36665502], [ 0.12711337, 0.17199144], [ 0.06886422, 0.08173259], [ 0.07495435, 0.73382897], [ 0.49609348, 0.4109899 ]])
np.diag(m)
array([1, 4])
np.trace(m)
5
m.T
matrix([[1, 3], [2, 4]])
m1 = np.linalg.inv(m)
m1
matrix([[-2. , 1. ], [ 1.5, -0.5]])
np.linalg.det(m)
-2.0000000000000004
np.linalg.det(m1)
-0.49999999999999967
[eival, eivec] = np.linalg.eig(m)
eival
array([-0.37228132, 5.37228132])
eivec
matrix([[-0.82456484, -0.41597356], [ 0.56576746, -0.90937671]])