Numpy Tutorial
A tutorial on Numpy
- Numpy Tutorial
- Built-ins
- Zeros and ones
- linspace
- eye
- Random
- seed
- Array Attributes and Methods
- Reshape
- max, min, argmax, argmin
- Shape
- dtype
- Bracket Indexing and Selection
- Broadcasting
- Indexing a 2D array (matrices)
- Conditional Selection
- Arithmetic
- Universal Array Functions
- Axis Logic
## import numpy
import numpy as np
my_lst = [1, 2, 3]
my_lst
np.array(my_lst)
my_matrix = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
my_matrix
np.array(my_matrix)
np.arange(0,11)
np.arange(0,11,2)
np.zeros(3)
np.zeros((3, 3))
np.ones(3)
np.ones((3, 3))
np.linspace(0, 10, 3)
np.linspace(0,5,20)
np.eye(4)
np.random.rand(2)
np.random.rand(5, 5)
np.random.randn(2)
np.random.randn(5, 5)
np.random.randint(1,100)
np.random.randint(1,100,10)
np.random.seed(42)
np.random.rand(4)
np.random.seed(42)
np.random.rand(4)
arr = np.arange(25)
ranarr = np.random.randint(0,50,10)
ranarr
arr
arr.reshape(5,5)
ranarr
ranarr.max()
ranarr.min()
ranarr.argmax()
ranarr.argmin()
arr.shape
# Notice the two sets of brackets
arr.reshape(1,25)
arr.reshape(1,25).shape
arr.reshape(25,1)
arr.reshape(25,1).shape
arr.dtype
arr2 = np.array([1.2, 3.4, 5.6])
arr2.dtype
#Get a value at an index
arr[8]
#Get values in a range
arr[1:5]
#Get values in a range
arr[0:5]
#Setting a value with index range (Broadcasting)
arr[0:5]=100
#Show
arr
# Reset array, we'll see why I had to reset in a moment
arr = np.arange(0,11)
#Show
arr
#Important notes on Slices
slice_of_arr = arr[0:6]
#Show slice
slice_of_arr
#Change Slice
slice_of_arr[:]=99
#Show Slice again
slice_of_arr
arr
#To get a copy, need to be explicit
arr_copy = arr.copy()
arr_copy
arr_2d = np.array(([5,10,15],[20,25,30],[35,40,45]))
#Show
arr_2d
#Indexing row
arr_2d[1]
#Indexing 2nc column
arr_2d[:,1]
# Format is arr_2d[row][col] or arr_2d[row,col]
# Getting individual element value
arr_2d[1][0]
# 2D array slicing
#Shape (2,2) from top right corner
arr_2d[:2,1:]
#Shape bottom row
arr_2d[2]
#Shape bottom row
arr_2d[2,:]
arr = np.arange(1,11)
arr
arr > 4
bool_arr = arr>4
bool_arr
arr[bool_arr]
arr[arr>2]
arr = np.arange(0, 11)
arr
arr + arr
arr * arr
arr - arr
# This will raise a Warning on division by zero, but not an error!
# It just fills the spot with nan
arr/arr
# Also a warning (but not an error) relating to infinity
1/arr
arr**3
# Taking Square Roots
np.sqrt(arr)
# Calculating exponential (e^)
np.exp(arr)
# Trigonometric Functions like sine
np.sin(arr)
# Taking the Natural Logarithm
np.log(arr)
arr_2d = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
arr_2d
arr_2d.sum(axis=0) #(columnwise)
arr_2d.sum(axis=1) #(rowwise)