Lab 1
Lab 1
Lab 1
Objectives: To create and use N-dimensional array structure with NumPy (2.1.2 or later) using
Python 3.12 or above.
NumPy (Numerical Python) is a powerful tool supported in python. It is a very fast while
computation when compared to other computational tools. NumPy’s main object is the
homogeneous multidimensional array. It is a table of elements (usually numbers), all of the same
type, indexed by a tuple of non-negative integers. In NumPy, dimensions are called axes.
import numpy as np
a = np.array([1, 2, 3])
Task(s):
1. Creates an array filled with 0’s (one-dimensional and two-dimensional)
2. Creates an array filled with 1’s (one-dimensional and two-dimensional)
3. Create an array that contains a range of evenly spaced intervals.
4. Create an array with values that are spaced linearly in a specified interval.
5. Explore more methods to create an ndarray object
arr = np.sort(arr)[::-1]
arr
Output:
a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
# Concatenate both arrays
np.concatenate((a, b))
Output:
Task(s):
1. Add elements to an ndarray
2. Remove element(s) from an ndarray
arr.size
Output:
arr.shape
Output:
4. Reshape an array
Using arr.reshape( ) will give a new shape to an array without changing the data. Remember that
when you use the reshape method, the array you want to produce must have the same number of
elements as the original array.
a = np.arange(6)
b = a.reshape(3, 2)
b
Output:
Output:
You can easily print all values in the array that are less than 5.
You can also select, for example, numbers that are equal to or greater than 5 and use that
condition to index an array.
five_up = (a >= 5)
print(a[five_up])
divisible_by_2 = a[a%2==0]
print(divisible_by_2)
Or you can select elements that satisfy two conditions using the “&” and “|” operators:
You can also use the logical operators “&” and “|” to return boolean values that specify whether
or not the values in an array fulfill a certain condition. This process can be useful for arrays
containing names or other categorical values.
five_up = (a > 5) | (a == 5)
print(five_up)
Basic operations are simple with NumPy. If you want to find the sum of the elements in an array.
a = np.array([1, 2, 3, 4])
a.sum( )
10
Output:
You would specify the axis to add the rows or columns in a 2D array.
Output
Lab Tasks
1. Empirically prove that NumPy ndarray is faster than Python List.
2. Write a python program to establish that NumPy ndarrays are more memory efficient
than Python List.
3. Are Numpy arrays more convenient than Python List?
Review Questions
Question 1: Enlist the data types supported in Numpy.