0% found this document useful (0 votes)
41 views

Numpy

Uploaded by

marcoloza65
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

Numpy

Uploaded by

marcoloza65
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

1D Numpy in

Python
Estimated time needed: 15 minutes

Objectives
After completing this lab you will be able to:

Import and use the numpy library


Perform operations with numpy

Table of Contents

What is Numpy?
Type
Assign Value
Slicing
Assign Value with List
Other Attributes
Numpy Array Operations
Array Addition
Array Multiplication
Product of Two Numpy Arrays
Dot Product
Adding Constant to a Numpy Array
Mathematical Functions
Linspace

What is Numpy?
NumPy is a Python library used for working with arrays, linear algebra, fourier transform, and
matrices. NumPy stands for Numerical Python and it is an open source project. The array
object in NumPy is called ndarray, it provides a lot of supporting functions that make
working with ndarray very easy.

Arrays are very frequently used in data science, where speed and resources are very
important.

NumPy is usually imported under the np alias.

It's usually fixed in size and each element is of the same type. We can cast a list to a numpy
array by first importing numpy :

In [1]: # import numpy library

import numpy as np

We then cast the list as follows:

In [2]: # Create a numpy array

a = np.array([0, 1, 2, 3, 4])
a

Out[2]: array([0, 1, 2, 3, 4])

Each element is of the same type, in this case integers:


As with lists, we can access each element via a square bracket:

In [3]: # Print each element

print("a[0]:", a[0])
print("a[1]:", a[1])
print("a[2]:", a[2])
print("a[3]:", a[3])
print("a[4]:", a[4])

a[0]: 0
a[1]: 1
a[2]: 2
a[3]: 3
a[4]: 4

Checking NumPy Version


The version string is stored under version attribute.

In [4]: print(np.__version__)

1.21.6

Type
If we check the type of the array we get numpy.ndarray:

In [5]: # Check the type of the array

type(a)

Out[5]: numpy.ndarray
As numpy arrays contain data of the same type, we can use the attribute "dtype" to obtain
the data type of the array’s elements. In this case, it's a 64-bit integer:

In [6]: # Check the type of the values stored in numpy array

a.dtype

Out[6]: dtype('int64')

Try it yourself
Check the type of the array and Value type for the given array c

In [7]: b = np.array([3.1, 11.02, 6.2, 213.2, 5.2])

# Enter your code here

Click here for the solution

Assign value
We can change the value of the array. Consider the array c :

In [8]: # Create numpy array

c = np.array([20, 1, 2, 3, 4])
c

Out[8]: array([20, 1, 2, 3, 4])

We can change the first element of the array to 100 as follows:

In [9]: # Assign the first element to 100

c[0] = 100
c

Out[9]: array([100, 1, 2, 3, 4])

We can change the 5th element of the array to 0 as follows:

In [10]: # Assign the 5th element to 0

c[4] = 0
c

Out[10]: array([100, 1, 2, 3, 0])

Try it yourself
Assign the value 20 for the second element in the given array.

In [11]: a = np.array([10, 2, 30, 40,50])

# Enter your code here

Click here for the solution

Slicing
Like lists, we can slice the numpy array. Slicing in python means taking the elements from
the given index to another given index.

We pass slice like this: [start:end].The element at end index is not being included in the
output.

We can select the elements from 1 to 3 and assign it to a new numpy array d as follows:

In [12]: # Slicing the numpy array

d = c[1:4]
d

Out[12]: array([1, 2, 3])

We can assign the corresponding indexes to new values as follows:

In [13]: # Set the fourth element and fifth element to 300 and 400

c[3:5] = 300, 400


c

Out[13]: array([100, 1, 2, 300, 400])

We can also define the steps in slicing, like this: [start:end:step].

In [14]: arr = np.array([1, 2, 3, 4, 5, 6, 7])

print(arr[1:5:2])

[2 4]

If we don't pass start its considered 0

In [15]: print(arr[:4])

[1 2 3 4]

If we don't pass end it considers till the length of array.

In [16]: print(arr[4:])
[5 6 7]

If we don't pass step its considered 1

In [17]: print(arr[1:5:])

[2 3 4 5]

Try it yourself
Print the even elements in the given array.

In [81]: arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])


print(arr[1:8:2])
# Enter your code here

[2 4 6 8]

Click here for the solution

Assign Value with List


Similarly, we can use a list to select more than one specific index. The list select contains
several values:

In [19]: # Create the index list

select = [0, 2, 3, 4]
select

Out[19]: [0, 2, 3, 4]

We can use the list as an argument in the brackets. The output is the elements
corresponding to the particular indexes:

In [20]: # Use List to select elements

d = c[select]
d

Out[20]: array([100, 2, 300, 400])

We can assign the specified elements to a new value. For example, we can assign the values
to 100 000 as follows:

In [21]: # Assign the specified elements to new value

c[select] = 100000
c

Out[21]: array([100000, 1, 100000, 100000, 100000])


Other Attributes
Let's review some basic array attributes using the array a :

In [22]: # Create a numpy array

a = np.array([0, 1, 2, 3, 4])
a

Out[22]: array([0, 1, 2, 3, 4])

The attribute size is the number of elements in the array:

In [23]: # Get the size of numpy array

a.size

Out[23]: 5

The next two attributes will make more sense when we get to higher dimensions but let's
review them. The attribute ndim represents the number of array dimensions, or the rank of
the array. In this case, one:

In [24]: # Get the number of dimensions of numpy array

a.ndim

Out[24]: 1

The attribute shape is a tuple of integers indicating the size of the array in each dimension:

In [25]: # Get the shape/size of numpy array

a.shape

Out[25]: (5,)

Try it yourself
Find the size ,dimension and shape for the given array b

In [84]: b = np.array([10, 20, 30, 40, 50, 60, 70])


print("Size=",b.size,"\nDimensions=",b.ndim,"\nShape",b.shape)
# Enter your code here

Size= 7
Dimensions= 1
Shape (7,)

Click here for the solution


Numpy Statistical Functions
In [85]: # Create a numpy array

a = np.array([1, -1, 1, -1])

In [86]: # Get the mean of numpy array

mean = a.mean()
mean

Out[86]: 0.0

In [87]: # Get the standard deviation of numpy array

standard_deviation=a.std()
standard_deviation

Out[87]: 1.0

In [88]: # Create a numpy array

b = np.array([-1, 2, 3, 4, 5])
b

Out[88]: array([-1, 2, 3, 4, 5])

In [89]: # Get the biggest value in the numpy array

max_b = b.max()
max_b

Out[89]: 5

In [32]: # Get the smallest value in the numpy array

min_b = b.min()
min_b

Out[32]: -1

Try it yourself
Find the sum of maximum and minimum value in the given numpy array

In [90]: c = np.array([-10, 201, 43, 94, 502])

# Enter your code here


max_c = c.max()
print("Maximum",max_c)

min_c = c.min()
print("Minnimum",min_c)

Sum = (max_c +min_c)


print("Max+Min",Sum)

Maximum 502
Minnimum -10
Max+Min 492

Click here for the solution

Numpy Array Operations


You could use arithmetic operators directly between NumPy arrays

Array Addition
Consider the numpy array u :

In [34]: u = np.array([1, 0])


u

Out[34]: array([1, 0])

Consider the numpy array v :

In [35]: v = np.array([0, 1])


v

Out[35]: array([0, 1])

We can add the two arrays and assign it to z:

In [36]: # Numpy Array Addition

z = np.add(u, v)
z

Out[36]: array([1, 1])

The operation is equivalent to vector addition:

In [37]: # Plotting functions

import time
import sys
import numpy as np

import matplotlib.pyplot as plt

def Plotvec1(u, z, v):

ax = plt.axes() # to generate the full window axes


ax.arrow(0, 0, *u, head_width=0.05, color='r', head_length=0.1)# Add an arrow t
plt.text(*(u + 0.1), 'u')#Adds the text u to the Axes

ax.arrow(0, 0, *v, head_width=0.05, color='b', head_length=0.1)# Add an arrow t


plt.text(*(v + 0.1), 'v')#Adds the text v to the Axes

ax.arrow(0, 0, *z, head_width=0.05, head_length=0.1)


plt.text(*(z + 0.1), 'z')#Adds the text z to the Axes
plt.ylim(-2, 2)#set the ylim to bottom(-2), top(2)
plt.xlim(-2, 2)#set the xlim to left(-2), right(2)

In [38]: # Plot numpy arrays

Plotvec1(u, z, v)

Try it yourself
Perform addition operation on the given numpy array arr1 and arr2:
In [91]: arr1 = np.array([10, 11, 12, 13, 14, 15])
arr2 = np.array([20, 21, 22, 23, 24, 25])
arr3 = np.add(arr1, arr2)
arr3
# Enter your code here

Out[91]: array([30, 32, 34, 36, 38, 40])

Click here for the solution

Array Subtraction
Consider the numpy array a:

In [40]: a = np.array([10, 20, 30])


a

Out[40]: array([10, 20, 30])

Consider the numpy array b:

In [41]: b = np.array([5, 10, 15])


b

Out[41]: array([ 5, 10, 15])

We can subtract the two arrays and assign it to c:

In [94]: max_c
min_c

Out[94]: -10

In [42]: c = np.subtract(a, b)

print(c)

[ 5 10 15]

Try it yourself
Perform subtraction operation on the given numpy array arr1 and arr2:

In [95]: arr1 = np.array([10, 20, 30, 40, 50, 60])


arr2 = np.array([20, 21, 22, 23, 24, 25])

# Enter your code here


arr3 = np.subtract(arr1, arr2)
arr3

Out[95]: array([-10, -1, 8, 17, 26, 35])


Click here for the solution

Array Multiplication
Consider the vector numpy array y :

In [44]: # Create a numpy array

x = np.array([1, 2])
x

Out[44]: array([1, 2])

In [45]: # Create a numpy array

y = np.array([2, 1])
y

Out[45]: array([2, 1])

We can multiply every element in the array by 2:

In [46]: # Numpy Array Multiplication

z = np.multiply(x, y)
z

Out[46]: array([2, 2])

This is equivalent to multiplying a vector by a scaler:

Try it yourself
Perform multiply operation on the given numpy array arr1 and arr2:

In [96]: arr1 = np.array([10, 20, 30, 40, 50, 60])


arr2 = np.array([2, 1, 2, 3, 4, 5])

# Enter your code here


arr3 = np.multiply(arr1, arr2)
arr3

Out[96]: array([ 20, 20, 60, 120, 200, 300])

Click here for the solution

Array Division
Consider the vector numpy array a:
In [48]: a = np.array([10, 20, 30])
a

Out[48]: array([10, 20, 30])

Consider the vector numpy array b:

In [49]: b = np.array([2, 10, 5])


b

Out[49]: array([ 2, 10, 5])

We can divide the two arrays and assign it to c:

In [50]: c = np.divide(a, b)
c

Out[50]: array([5., 2., 6.])

Try it yourself
Perform division operation on the given numpy array arr1 and arr2:

In [97]: arr1 = np.array([10, 20, 30, 40, 50, 60])


arr2 = np.array([3, 5, 10, 8, 2, 33])

# Enter your code here


arr3 = np.divide(arr1, arr2)
arr3

Out[97]: array([ 3.33333333, 4. , 3. , 5. , 25. ,


1.81818182])

Click here for the solution

Dot Product
The dot product of the two numpy arrays u and v is given by:

In [52]: X = np.array([1, 2])


Y = np.array([3, 2])

In [53]: # Calculate the dot product

np.dot(X, Y)

Out[53]: 7

In [54]: #Elements of X
print(X[0])
print(X[1])

1
2

In [55]: #Elements of Y
print(Y[0])
print(Y[1])

3
2

We are performing the dot product which is shown as below

Try it yourself
Perform dot operation on the given numpy array ar1 and ar2:

In [98]: arr1 = np.array([3, 5])


arr2 = np.array([2, 4])

# Enter your code here


arr3 = np.dot(arr1, arr2)
arr3

Out[98]: 26

Click here for the solution

Adding Constant to a Numpy Array


Consider the following array:
In [57]: # Create a constant to numpy array

u = np.array([1, 2, 3, -1])
u

Out[57]: array([ 1, 2, 3, -1])

Adding the constant 1 to each element in the array:

In [58]: # Add the constant to array

u + 1

Out[58]: array([2, 3, 4, 0])

The process is summarised in the following animation:

Try it yourself
Add Constant 5 to the given numpy array ar:

In [99]: arr = np.array([1, 2, 3, -1])

# Enter your code here


arr + 5

Out[99]: array([6, 7, 8, 4])

Click here for the solution

Mathematical Functions
We can access the value of pi in numpy as follows :
In [60]: # The value of pi

np.pi

Out[60]: 3.141592653589793

We can create the following numpy array in Radians:

In [61]: # Create the numpy array in radians

x = np.array([0, np.pi/2 , np.pi])

We can apply the function sin to the array x and assign the values to the array y ; this
applies the sine function to each element in the array:

In [62]: # Calculate the sin of each elements

y = np.sin(x)
y

Out[62]: array([0.0000000e+00, 1.0000000e+00, 1.2246468e-16])

Linspace
A useful function for plotting mathematical functions is linspace . Linspace returns evenly
spaced numbers over a specified interval.

numpy.linspace(start, stop, num = int value)

start : start of interval range

stop : end of interval range

num : Number of samples to generate.

In [63]: # Makeup a numpy array within [-2, 2] and 5 elements

np.linspace(-2, 2, num=5)

Out[63]: array([-2., -1., 0., 1., 2.])

If we change the parameter num to 9, we get 9 evenly spaced numbers over the interval
from -2 to 2:

In [64]: # Make a numpy array within [-2, 2] and 9 elements

np.linspace(-2, 2, num=9)
Out[64]: array([-2. , -1.5, -1. , -0.5, 0. , 0.5, 1. , 1.5, 2. ])

We can use the function linspace to generate 100 evenly spaced samples from the
interval 0 to 2π:

In [65]: # Make a numpy array within [0, 2π] and 100 elements

x = np.linspace(0, 2*np.pi, num=100)

We can apply the sine function to each element in the array x and assign it to the array y :

In [66]: # Calculate the sine of x list

y = np.sin(x)

In [67]: # Plot the result

plt.plot(x, y)

Out[67]: [<matplotlib.lines.Line2D at 0x7f12d20a79d0>]

Try it yourself
Make a numpy array within [5, 4] and 6 elements

In [100… # Enter your code here


np.linspace(5, 4, num=6)
Out[100]: array([5. , 4.8, 4.6, 4.4, 4.2, 4. ])

Click here for the solution

Iterating 1-D Arrays


Iterating means going through elements one by one.

If we iterate on a 1-D array it will go through each element one by one.

If we execute the numpy array, we get in the array format

In [69]: arr1 = np.array([1, 2, 3])


print(arr1)

[1 2 3]

But if you want to result in the form of the list, then you can use for loop:

In [70]: for x in arr1:


print(x)

1
2
3

Quiz on 1D Numpy Array


Implement the following vector subtraction in numpy: u-v

In [101… # Write your code below and press Shift+Enter to execute

u = np.array([1, 0])
v = np.array([0, 1])
u - v

Out[101]: array([ 1, -1])

Click here for the solution

Multiply the numpy array z with -2:

In [102… # Write your code below and press Shift+Enter to execute

z = np.array([2, 4])
-2 * z
Out[102]: array([-4, -8])

Click here for the solution

Consider the list [1, 2, 3, 4, 5] and [1, 0, 1, 0, 1] . Cast both lists to a numpy
array then multiply them together:

In [103… # Write your code below and press Shift+Enter to execute


a = np.array([1, 2, 3, 4, 5])
b = np.array([1, 0, 1, 0, 1])
a * b

Out[103]: array([1, 0, 3, 0, 5])

Click here for the solution

In [106… # Import the libraries

import time
import sys
import numpy as np

import matplotlib.pyplot as plt

def Plotvec2(a,b):
ax = plt.axes()# to generate the full window axes
ax.arrow(0, 0, *a, head_width=0.05, color ='r', head_length=0.1)#Add an arrow t
plt.text(*(a + 0.1), 'a')
ax.arrow(0, 0, *b, head_width=0.05, color ='b', head_length=0.1)#Add an arrow t
plt.text(*(b + 0.1), 'b')
plt.ylim(-2, 2)#set the ylim to bottom(-2), top(2)
plt.xlim(-2, 2)#set the xlim to left(-2), right(2)

Convert the list [-1, 1] and [1, 1] to numpy arrays a and b . Then, plot the arrays as
vectors using the fuction Plotvec2 and find their dot product:

In [75]: # Write your code below and press Shift+Enter to execute

Click here for the solution

Convert the list [1, 0] and [0, 1] to numpy arrays a and b . Then, plot the arrays as
vectors using the function Plotvec2 and find their dot product:
In [107… # Write your code below and press Shift+Enter to execute
a = np.array([1, 0])
b = np.array([0, 1])
Plotvec2(a, b)
print("The dot product is", np.dot(a, b))

The dot product is 0

Click here for the solution

Convert the list [1, 1] and [0, 1] to numpy arrays a and b . Then plot the arrays as
vectors using the fuction Plotvec2 and find their dot product:

In [108… # Write your code below and press Shift+Enter to execute


a = np.array([1, 1])
b = np.array([0, 1])
Plotvec2(a, b)
print("The dot product is", np.dot(a, b))

The dot product is 1


Click here for the solution

Why are the results of the dot product for [-1, 1] and [1, 1] and the dot product for
[1, 0] and [0, 1] zero, but not zero for the dot product for [1, 1] and [0, 1] ?

Hint: Study the corresponding figures, pay attention to the direction the arrows are pointing to.

The vectors used for question 4 and 5 are perpendicular. As a result, the dot product is zero.
Click here for the solution

Convert the list [1, 2, 3] and [8, 9, 10] to numpy arrays arr1 and arr2 . Then
perform Addition , Subtraction , Multiplication , Division and Dot
Operation on the arr1 and arr2 .

In [111… # Write your code below and press Shift+Enter to execute


arr1 = np.array([1, 2, 3])
arr2 = np.array([8, 9, 10])

arr3 = np.add(arr1, arr2)


print(arr3)

arr4 = np.subtract(arr1, arr2)


print(arr4)

arr5 = np.multiply(arr1, arr2)


print(arr5)

arr6 = np.divide(arr1, arr2)


print(arr6)

arr7 = np.dot(arr1, arr2)


print(arr7)

[ 9 11 13]
[-7 -7 -7]
[ 8 18 30]
[0.125 0.22222222 0.3 ]
56

Click here for the solution

Convert the list [1, 2, 3, 4, 5] and [6, 7, 8, 9, 10] to numpy arrays arr1 and
arr2 . Then find the even and odd numbers from arr1 and arr2 .

In [112… # Write your code below and press Shift+Enter to execute

arr1 = np.array([1, 2, 3, 4, 5])


arr2 = np.array([6, 7, 8, 9, 10])

#Starting index in slice is 1 as first even element(2) in array1 is at index 1


even_arr1 = arr1[1:5:2]
print("even for array1",even_arr1)

#Starting index in slice is 0 as first odd element(1) in array1 is at index 0


odd_arr1=arr1[0:5:2]
print("odd for array1",odd_arr1)

#Starting index in slice is 0 as first even element(6) in array2 is at index 0


even_arr2 = arr2[0:5:2]
print("even for array2",even_arr2)

#Starting index in slice is 1 as first odd element(7) in array2 is at index 1


odd_arr2=arr2[1:5:2]
print("odd for array2",odd_arr2)

even for array1 [2 4]


odd for array1 [1 3 5]
even for array2 [ 6 8 10]
odd for array2 [7 9]

Click here for the solution

Author
Dev Agnihotri

You might also like