import numpy as np
np.array([1,2,3])
np.array([[1,2,3], [4,5,6]])
np.array([[[1,2], [3,4]], [[5,6], [7,8]]])
np.zeros((3,4)) # matrix with all elements being zero
np.zeros((3,4), dtype=int) # specify that elements are ints instead of floats
np.ones((2,3)) # initializes all elements to one
np.full((2,3), fill_value=7) # initializes all elements to a specified value (here 7)
np.empty((2,4)) # leaves the elements uninitialized
np.eye(5, dtype=int) # creates the identity matrix
np.arange(0,10,2) # like the range function, but produces an array instead of a list.
np.linspace(0, np.pi, 5) # Evenly spaced range with 5 elements
np.random.uniform(0, 1, size=(3,4)) # Elements are uniformly distributed from half-open interval [0.0,1.0)
np.random.normal(0, 1, (3,4)) # Elements are normally distributed with mean 0 and standard deviation 1
np.random.randint(-2, 10, (3,4)) # Elements are uniformly distributed integers from the half-open interval [-2,10)
## Global
np.random.seed(0)
print(np.random.randint(0, 100, 10))
print(np.random.normal(0, 1, 10))
## Local
new_generator = np.random.RandomState(seed=123) # RandomState is a class, so we give the seed to its constructor
new_generator.randint(0, 100, 10)
Functions in numpy.random
seed
permutation
rand
randint
randn
binomial
normal
beta
chisquare
gamma
uniform
ndim
tells the number of dimensions, shape
tells the size in each dimension, size
tells the number of elements, dtype
tells the element type.b=np.array([[1,2,3], [4,5,6]])
b.ndim
b.shape
b.size
b.dtype
b=np.array([[1,2,3], [4,5,6]])
print(b)
print(b[1,2]) # row index 1, column index 2
print(b[0,-1]) # row index 0, column index -1
print(b[0]) # First row
print(b[1]) # Second row
# As with lists, modification through indexing is possible
b[0,0] = 10
print(b)
a=np.array([1,4,2,7,9,5])
print(a)
print(a[1:3])
print(a[::-1]) # Reverses the array
print(b)
print(b[:,0]) # First column
print(b[0,:]) # First row
print(b[:,1:]) # Except the first column
print(b[:, [1,3]])
d=np.arange(4) # 1d array
dr=d.reshape(1,4) # row vector
dc=d.reshape(4,1) # column vector
print(d)
print(dr)
print(d[np.newaxis, :]) # alternative way
print(dc)
print(d[:, np.newaxis]) # alternative way
a=np.random.randint(0, 10, (4,4))
print(a)
print(a.T)
The are two ways of combining several arrays into one bigger array:
Concatenate
takes n-dimensional arrays and returns an n-dimensional arrayStack
takes n-dimensional arrays and returns n+1-dimensional array. Inverse operation of concatenate
is split
.
a=np.arange(2)
b=np.arange(2,5)
print(f"a has shape {a.shape}: {a}")
print(f"b has shape {b.shape}: {b}")
np.concatenate((a,b)) # concatenating 1d arrays
c=np.arange(1,5).reshape(2,2)
print(f"c has shape {c.shape}:", c, sep="\n")
np.concatenate((c,c)) # concatenating 2d arrays
np.concatenate((c,c), axis=1)
np.stack((b,b))
np.stack((b,b), axis=1)
If you want to catenate arrays with different dimensions, for example to add a new column to a 2d array, you must first reshape the arrays to have same number of dimensions:
print(a)
print("New row:")
print(np.concatenate((c,a.reshape(1,2))))
## split
d=np.arange(12).reshape(6,2)
print("d:")
print(d)
d1,d2 = np.split(d, 2) # specify the number of equal parts the array is divided into,
print("d1:")
print(d1)
print("d2:")
print(d2)
d=np.arange(12).reshape(2,6)
print("d:")
print(d)
parts=np.split(d, (2,3,5), axis=1) # specify explicitly the break points
for i, p in enumerate(parts):
print("part %i:" % i)
print(p)
max
, min
, sum
, mean
, std
, …np.random.seed(0)
a=np.random.randint(-100, 100, (4,5))
print(a)
print(f"Minimum: {a.min()}, maximum: {a.max()}")
print(f"Sum: {a.sum()}")
print(f"Mean: {a.mean()}, standard deviation: {a.std()}")
np.random.seed(9)
b=np.random.randint(0, 10, (3,4))
print(b)
print("Column sums:", b.sum(axis=0))
print("Row sums:", b.sum(axis=1))
a=np.array([1,3,4])
b=np.array([2,2,7])
c = a < b
print(c)
print(c.all()) # were all True
print(c.any()) # was some comparison True
print(np.sum(c))
import pandas as pd
a=pd.read_csv("kumpula-weather-2017.csv")['Air temperature (degC)'].values
a[:6]
print("Number of days with the temperature below zero", np.sum(a < 0))
np.sum((0 < a) & (a < 10))
c = a > 0
print(c[:10]) # print only the first ten elements
print(a[c]) # Select only the positive temperatures
a[~c] = 0
print(a[:6])
a=np.array([2,1,4,3,5])
print(np.sort(a)) # Does not modify the argument
print(a)
a.sort() # Modifies the argument
print(a)
a=np.array([23,12,47,35,59])
print("Array a:", a)
idx = np.argsort(a)
print("Indices:", idx)
np.random.seed(0)
a=np.random.randint(0,10, (3,2))
b=np.random.randint(0,10, (2,4))
print(a)
print(b)
print(np.matmul(a,b))
print(a@b)
## Invertible matrix
s=np.array([[1, 6, 7],
[7, 8, 1],
[5, 9, 8]])
print("Original matrix:", s, sep="\n")
s_inv = np.linalg.inv(s)
print("Inverted matrix:", s_inv, sep="\n")
print("Matrix product:", s @ s_inv, sep="\n") # This should be pretty close to the identity matrix np.eye(3)
print("Matrix product the other way:", s_inv @ s, sep="\n")
np.linalg.solve
a = np.array([[3,1], [1,2]])
b = np.array([9,8])
print(np.linalg.solve(a, b))