Skip to content

Instantly share code, notes, and snippets.

@vhsu
Last active June 19, 2024 19:19
Show Gist options
  • Save vhsu/d474ebfa7e3883d22e82d6003b9c84d0 to your computer and use it in GitHub Desktop.
Save vhsu/d474ebfa7e3883d22e82d6003b9c84d0 to your computer and use it in GitHub Desktop.
Numpy basics

check https://github.com/KeithGalli/NumPy/blob/master/NumPy%20Tutorial.ipynb and https://www.youtube.com/watch?v=QUT1VHiLmmI&t=2134s

import numpy as np
x = np.array([[1,2,3],[3,4,5],[1,2,5]])

Print inverse

if np.linalg.det(x) != 0:
    # Calculate the inverse
    inverse_x = np.linalg.inv(x)
    print("Inverse of the matrix x:")
    print(inverse_x)
else:
    print("The matrix is not invertible.")
Inverse of the matrix x:
[[-2.5  1.   0.5]
 [ 2.5 -0.5 -1. ]
 [-0.5  0.   0.5]]

Find transpose

# Calculate the transpose using the .T attribute
transpose_x = x.T
transpose_x = np.transpose(transpose_x)
print("Transpose of the matrix x:")
print(transpose_x)
Transpose of the matrix x:
[[1 2 3]
 [3 4 5]
 [1 2 5]]

Print dimension

print(x.ndim)
print(transpose_x.ndim)
2
2
print(x)
[[1 2 3]
 [3 4 5]
 [1 2 3]]

Get shape, type and size

x.shape
(3, 3)
x.dtype
dtype('int32')
x.size
9
x.itemsize
4

Access specific elements

#get a specific element [r,c]
x[1,2]
5
#get a row
x[0,:]
array([1, 2, 3])
#get column
x[ : ,0]
array([1, 3, 1])

Get identity and zero matrices

#get identity
np.eye(3,4)
array([[1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 1., 0.]])
np.identity(3)
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
np.zeros(x.shape)
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])
np.zeros((2,2))
array([[0., 0.],
       [0., 0.]])
np.eye(3)
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
np.eye(x.shape[0])
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])

create a matrix of same shape

#create a matrix full of 4s that is the same shape as x
np.full_like(x,4
array([[4, 4, 4],
       [4, 4, 4],
       [4, 4, 4]])
#you could also use full
np.full(x.shape,4)
array([[4, 4, 4],
       [4, 4, 4],
       [4, 4, 4]])

Random Matrix

np.random.rand(4,2)
array([[0.32959854, 0.26420155],
       [0.80235474, 0.50089219],
       [0.79643353, 0.07653959],
       [0.81367105, 0.08780162]])
np.random.random_sample(x.shape)
array([[0.25710446, 0.60448653, 0.04779258],
       [0.90395406, 0.05342086, 0.32161916],
       [0.4441867 , 0.87693879, 0.06256832]])
np.random.randint(10,size=(3,3))
#0 to 10
array([[9, 3, 4],
       [4, 7, 0],
       [8, 7, 3]])

Repeat

z = np.array([[1,2,3]])
r1 = np.repeat(z,3,axis=0)
print(r1)
[[1 2 3]
 [1 2 3]
 [1 2 3]]

Be careful while copying (in numpy copies are made by reference)

ar1 = np.array([1,2,3])
ar2 = ar1
ar2[0]=100
print(ar2)
print(ar1)
[100   2   3]
[100   2   3]
#to copy by value and not by reference add .copy()
ar1 = np.array([1,2,3])
ar2 = ar1.copy()
ar2[0]=100
print(ar2)
print(ar1)
[100   2   3]
[1 2 3]

Mathematics

a = np.array([1,2,3])
print(a + 2)
[3 4 5]
print(a*3)
[3 6 9]
b = np.array([5,7,2])
print(a + b)
[6 9 5]
print(a**2)
[1 4 9]

Linear algebra

a = np.full((3,3),2)
print(a)
b=np.ones((3,3))
print(b)
[[2 2 2]
 [2 2 2]
 [2 2 2]]
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
print(a@b) #dot product
[[6. 6. 6.]
 [6. 6. 6.]
 [6. 6. 6.]]
np.linalg.det(np.identity(3)) #determinant
1.0
a = np.full((3,2),2)
print(a)
b=np.ones((2,3))
print(b)
[[2 2]
 [2 2]
 [2 2]]
[[1. 1. 1.]
 [1. 1. 1.]]
np.matmul(b,a) #matrix multiplication
array([[6., 6.],
       [6., 6.]])

Statistics

stats = np.array([[1,2,3],[4,5,6]])
np.min(stats)
1
np.min(stats,axis=0)
array([1, 2, 3])
np.min(stats,axis=1)
array([1, 4])
np.max(stats)
6
np.sum(stats,axis=0)
array([5, 7, 9])
np.mean(stats)
3.5
np.var(stats)
2.9166666666666665
np.std(stats,axis=1)
array([0.81649658, 0.81649658])

Reshape

before = np.array([[1,2,3,4],[5,6,7,8]])
print(before)

after = before.reshape((4,2))
print(after)
[[1 2 3 4]
 [5 6 7 8]]
[[1 2]
 [3 4]
 [5 6]
 [7 8]]

Vertical staking (hstack for horizontal stacking)

# Vertically stacking vectors
v1 = np.array([1,2,3,4])
v2 = np.array([5,6,7,8])

np.vstack([v1,v2,v1,v2])
array([[1, 2, 3, 4],
       [5, 6, 7, 8],
       [1, 2, 3, 4],
       [5, 6, 7, 8]])

Load data from file

#for a comma seperated txt file
filedata = np.genfromtxt('data.txt', delimiter = ',')
---------------------------------------------------------------------------

FileNotFoundError                         Traceback (most recent call last)

Cell In[296], line 2
      1 #for a comma seperated txt file
----> 2 np.genfromtxt('data.txt', delimiter = ',')


File ~\anaconda3\Lib\site-packages\numpy\lib\npyio.py:1980, in genfromtxt(fname, dtype, comments, delimiter, skip_header, skip_footer, converters, missing_values, filling_values, usecols, names, excludelist, deletechars, replace_space, autostrip, case_sensitive, defaultfmt, unpack, usemask, loose, invalid_raise, max_rows, encoding, ndmin, like)
   1978     fname = os_fspath(fname)
   1979 if isinstance(fname, str):
-> 1980     fid = np.lib._datasource.open(fname, 'rt', encoding=encoding)
   1981     fid_ctx = contextlib.closing(fid)
   1982 else:


File ~\anaconda3\Lib\site-packages\numpy\lib\_datasource.py:193, in open(path, mode, destpath, encoding, newline)
    156 """
    157 Open `path` with `mode` and return the file object.
    158 
   (...)
    189 
    190 """
    192 ds = DataSource(destpath)
--> 193 return ds.open(path, mode, encoding=encoding, newline=newline)


File ~\anaconda3\Lib\site-packages\numpy\lib\_datasource.py:533, in DataSource.open(self, path, mode, encoding, newline)
    530     return _file_openers[ext](found, mode=mode,
    531                               encoding=encoding, newline=newline)
    532 else:
--> 533     raise FileNotFoundError(f"{path} not found.")


FileNotFoundError: data.txt not found.
filedata = np.array([[  1,13  ,21,  11, 196 , 75,   4 ,  3 , 34,6,   7,   8  , 0 ,  1 ,  2,3,4,5],
 [3 , 42 , 12,33, 766,75  , 4 , 55,6,4  , 3  , 4 ,  5,6,7  , 0,11 , 12],
 [  1 , 22 , 33 , 11, 999,  11 ,  2  , 1  ,78  , 0 ,  1  , 2  , 9 ,  8  , 7  , 1 , 76 , 88]])
filedata > 50
array([[False, False, False, False,  True,  True, False, False, False,
        False, False, False, False, False, False, False, False, False],
       [False, False, False, False,  True,  True, False,  True, False,
        False, False, False, False, False, False, False, False, False],
       [False, False, False, False,  True, False, False, False,  True,
        False, False, False, False, False, False, False,  True,  True]])
filedata[filedata > 50]
array([196,  75, 766,  75,  55, 999,  78,  76,  88])
((filedata > 50) & (filedata < 100))
array([[False, False, False, False, False,  True, False, False, False,
        False, False, False, False, False, False, False, False, False],
       [False, False, False, False, False,  True, False,  True, False,
        False, False, False, False, False, False, False, False, False],
       [False, False, False, False, False, False, False, False,  True,
        False, False, False, False, False, False, False,  True,  True]])
#inverse (not)
(~((filedata > 50) & (filedata < 100)))
array([[ True,  True,  True,  True,  True, False,  True,  True,  True,
         True,  True,  True,  True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True, False,  True, False,  True,
         True,  True,  True,  True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True,  True,  True, False,
         True,  True,  True,  True,  True,  True,  True, False, False]])
#to find if any value in any column is > 50
np.any(filedata > 50, axis = 0)
array([False, False, False, False,  True,  True, False,  True,  True,
       False, False, False, False, False, False, False,  True,  True])
#to find if all values in any column is > 50
np.all(filedata > 50, axis = 0)
array([False, False, False, False,  True, False, False, False, False,
       False, False, False, False, False, False, False, False, False])
#to find if all values in any rowcolumn is > 50
np.all(filedata > 50, axis = 1)
array([False, False, False])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment