Python Programmer Logo Python Programmer Python Programmer Logo


Numpy Libary Showcase

Below are the python files I used in this video and the actual video


The video files

File Download Date Modified
Broadcasting (Tips and Tricks 1) Download File 24 Feb 2024
Structured Arrays (Tips and Tricks 2) Download File 24 Feb 2024
Fancy Indexing (Tips and Tricks 3) Download File 25 Feb 2024
Vectorisation (Tips and Tricks 4) Download File 25 Feb 2024

The actual code in the files

Broadcasting


#Numpy tips and tricks 1
import numpy as np

a = np.array([5,3,7])
b = 2

print(a+b)
"""Here this is called broadcasting, it allow the operator
addition to be applied between b and a element-wise, even
though b is just a numbver and a is an array it will add
b to each element of a"""

#Now let's run it

Structured Arrays


#Numpy tips and tricks 2
import numpy as np

#We have to define data types for an array
dt = np.dtype([('name', np.str_, 16),
               ('age', np.int32),
               ('weight', np.float64)])

#Now we can create a structured array
data = np.array([('Jake', 19, 74.5),
                 ('Sally', 23, 64.3),
                 ('Jack', 16, 78.9)], dtype=dt)

#print(data)

#Now let's run it

#There are also more useful fetaures to this

print("Names:",data['name'])
print("Ages:",data['age'])
print("Weights:",data['weight'])

#You can also change a field directly
data['weight'][0] = 75.7

print("New weights:",data['weight'])

#You can also print out a record like this
print(data[0]['name'],"has info:",data[0])

Fancy Indexing


#Numpy tips and ticks 3
import numpy as np

a = np.array([1,4,8,6,9,2])

#You can select elements by index

print(a[[1, 5, 2]])

#You can also modify elements like this
a[[1,2,3]] = 0
print(a)

Vectorisation


#Numpy tips and tricks 4
import numpy as np
import timeit

#First we will create two random number arrays
a = np.random.rand(100000)
b = np.random.rand(100000)

def dot_product1():
    dot_product = 0
    for num in range(len(a)):
        dot_product += a[num] * b[num]
    print(dot_product)

def dot_product2():
    dot_product = np.dot(a, b)
    print(dot_product)

time1 = timeit.timeit(lambda: dot_product1, number=1)

time2 = timeit.timeit(lambda: dot_product2, number=1)

"""Here we have put the two dot_product codes in their
own functions and we're going to time how long they each
take to run only 1 time"""

print("Function 1 took",time1,"seconds to run")
print("Function 2 took",time2,"seconds to run")

#We can also use vectorisation with angles

angles_deg = np.array([0,30,45,60,90])

#Now we will use the vectorisation to convert the angles
angles_rad = np.radians(angles_deg)

print(angles_rad)