Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Lab 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Lab No.

Student Name/Roll No:

Lab Instructor Signatures: Date:

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.

1. Creating Basic Array


To create a NumPy array, you can use the function np.array( ). All you need to do, to create a
simple array, is to pass a python list to np.array( ). You can also specify the data type in your list
if you choose to.

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

2. Adding, removing, and sorting elements


Sorting an element is simple with np.sort( ). When you call the np.sort( ) function, you can
specify the “axis”, “kind”, and “order”.

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


arr
Output:
# Sort in ascending order
np.sort(arr)
Output:

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:

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


y = np.array([[5, 6]])
np.concatenate((x, y), axis=0)
Output:

Task(s):
1. Add elements to an ndarray
2. Remove element(s) from an ndarray

3. How do you know the shape and size of an array?


This section will cover:

1. ndarray.ndim: It tells you the number of axes, or dimensions, of the array.


2. ndarray.size: It tells you the total number of elements of the array.
3. ndarray.shape:It will display a tuple of integers that indicate the number of elements
stored along each dimension of the array.
arr = np.array([[0, 1, 2, 3], [4, 5, 6, 7]])
arr.ndim
Output:

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:

With np.reshape, you can specify a few optional parameters:

np.reshape(a, newshape=(1, 6), order='C)

Output:

 “a” is the array to be reshaped.


 “newshape” is the required new shape. You can specify an integer or a tuple of integers.
If you select an integer, the result will be an array of that length. The shape should be
compatible with the original form. “order”: C means to read/write the elements using C-
like index order.

Task(s): Demonstrate the usage of other parameters of “C”.

5. Indexing and slicing


You can index and slice NumPy arrays in the same ways you can slice Python lists.

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


data[1]
2
data[0:2]
array([1, 2])
data[1:]
array([2, 3])
data[-2:]
array([2, 3])
If you want to select values from your array that fulfill certain conditions, it’s straightforward
with NumPy.

a = np.array([[1 , 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

You can easily print all values in the array that are less than 5.

print(a[a < 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])

You can select elements that are divisible by 2:

divisible_by_2 = a[a%2==0]
print(divisible_by_2)
Or you can select elements that satisfy two conditions using the “&” and “|” operators:

c = a[(a > 2) & (a < 11)]


print(c)

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)

Task(s): Explore more indexing options

6. Basic array operations


 Addition
 Subtraction
 Multiplication
 Division
Once you’ve created your arrays, you can start to work with them. Let’s say, for example, that
you’ve created two arrays, one called “data” and one called “ones”.

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


ones = np.ones(2, dtype=int)
data + ones
Output:

You can, of course, do more than just addition!


data - ones
array([0, 1])
data * data
array([1, 4])
data / data
array([1., 1.])
Output:

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.

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

Output

You can sum over the axis of rows with:


b.sum(axis=0)
array([3, 3])
Output:

You can sum over the axis of columns with:


b.sum(axis=1)
array([2, 4])
Task(s): Perform matrix multiplication

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.

You might also like