Lab Name:          To Apply Numbers Python ( Numpy ) for Data Processing and Optimization Techniques
Course title: Optimization Techniques                                                       Total Marks: ____________
      Practical No. 6                                                        Date of experiment performed: ____________
      Course teacher/Lab Instructor: Dr. Saif Ullah                                   Date of marking: ____________
      Student Name:__________________________
      Registration no.__________________________
            Marking Evaluation Sheet
 Knowledge components                             Domain                                 Contribution   Max.    Obtained
                                                                 Taxonomy level
                                                                                                        marks   marks
     1. Student has successfully imitated the                    Imitation (P1)                         2
        Nummy commands.
     2. Student has sliced an arrays in Python
                                                                 Manipulate (P2)                        2
        language. (Manipulation)
                                                  Psychomotor                            75%
3.     Student has applied addition and
                                                                 Manipulate (P2)                        2
       multiplication of a number in an array.
             (Manipulation)
        Student have successfully obtained
                                                                 Manipulate (P2)                        2
        mean, average, median, minimum and
        maximum in an array.
     4. Student was aware of safety time of
        the tasks given during lab duration and      Affective       Receiving (A1)                     1
        completed given tasks in time.
     5. Student contributed and responded
        effectively in the form of team or in a      Affective       Respond (A2)        5%             1
        group.
     6. Student submitted the lab reports in
        the deadline.                                Affective        Valuing (A3)                      1
     7. Student has learned and applied sets,
                                                  Cognitive      Analyze (C4)            20%            4
        tuples, functions, ifelse and nested
        ifelse commands of Python.
                                                                                         Total          15
                                                                                         Normalize
                                                                                         marks out of   5
                                                                                         (5)
            Signed by Course teacher/ Lab Instructor
Lab 06
OBJECTIVE:
        To Apply Numbers Python ( Numpy ) for Data Processing and Optimization Techniques.
APPARATUS USED:
Personal Computer, Internet facility, Python
How to create an array from existing data
This section covers slicing and indexing, np.vstack(), np.hstack(), np.hsplit(), .view(), copy()
You can easily use create a new array from a section of an existing array.
Let’s say you have this array:
>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
You can create a new array from a section of your array any time by specifying where you want
to slice your array.
>>> arr1 = a[3:8]
>>> arr1
array([4, 5, 6, 7, 8])
Here, you grabbed a section of your array from index position 3 through index position 8.
You can also stack two existing arrays, both vertically and horizontally. Let’s say you have two
arrays, a1 and a2:
>>> a1 = np.array([[1, 1],
...        [2, 2]])
>>> a2 = np.array([[3, 3],
...        [4, 4]])
You can stack them vertically with vstack:
>>> np.vstack((a1, a2))
array([[1, 1],
    [2, 2],
    [3, 3],
    [4, 4]])
Or stack them horizontally with hstack:
>>> np.hstack((a1, a2))
array([[1, 1, 3, 3],
    [2, 2, 4, 4]])
You can split an array into several smaller arrays using hsplit. You can specify either the number
of equally shaped arrays to return or the columns after which the division should occur.
Let’s say you have this array:
>>> x = np.arange(1, 25).reshape(2, 12)
>>> x
array([[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
    [13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]])
If you wanted to split this array into three equally shaped arrays, you would run:
>>> np.hsplit(x, 3)
[array([[1, 2, 3, 4],
     [13, 14, 15, 16]]), array([[ 5, 6, 7, 8],
     [17, 18, 19, 20]]), array([[ 9, 10, 11, 12],
     [21, 22, 23, 24]])]
If you wanted to split your array after the third and fourth column, you’d run:
>>> np.hsplit(x, (3, 4))
[array([[1, 2, 3],
     [13, 14, 15]]), array([[ 4],
     [16]]), array([[ 5, 6, 7, 8, 9, 10, 11, 12],
     [17, 18, 19, 20, 21, 22, 23, 24]])]
Learn more about stacking and splitting arrays here.
You can use the view method to create a new array object that looks at the same data as the
original array (a shallow copy).
Views are an important NumPy concept! NumPy functions, as well as operations like indexing
and slicing, will return views whenever possible. This saves memory and is faster (no copy of the
data has to be made). However it’s important to be aware of this - modifying data in a view also
modifies the original array!
Let’s say you create this array:
>>> a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
Now we create an array b1 by slicing a and modify the first element of b1. This will modify the
corresponding element in a as well!
>>> b1 = a[0, :]
>>> b1
array([1, 2, 3, 4])
>>> b1[0] = 99
>>> b1
array([99, 2, 3, 4])
>>> a
array([[99, 2, 3, 4],
    [ 5, 6, 7, 8],
    [ 9, 10, 11, 12]])
Using the copy method will make a complete copy of the array and its data (a deep copy). To use
this on your array, you could run:
>>> b2 = a.copy()
Learn more about copies and views here.
Basic array operations
This section covers addition, subtraction, multiplication, division, and more
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”
You can add the arrays together with the plus sign.
>>> data = np.array([1, 2])
>>> ones = np.ones(2, dtype=int)
>>> data + ones
array([2, 3])
You can, of course, do more than just addition!
>>> data - ones
array([0, 1])
>>> data * data
array([1, 4])
>>> data / data
array([1., 1.])
Basic operations are simple with NumPy. If you want to find the sum of the elements in an array,
you’d use sum(). This works for 1D arrays, 2D arrays, and arrays in higher dimensions.
>>> a = np.array([1, 2, 3, 4])
>>> a.sum()
10
To add the rows or the columns in a 2D array, you would specify the axis.
If you start with this array:
>>> b = np.array([[1, 1], [2, 2]])
You can sum over the axis of rows with:
>>> b.sum(axis=0)
array([3, 3])
You can sum over the axis of columns with:
>>> b.sum(axis=1)
array([2, 4])
Learn more about basic operations here.
Broadcasting
There are times when you might want to carry out an operation between an array and a single
number (also called an operation between a vector and a scalar) or between arrays of two
different sizes. For example, your array (we’ll call it “data”) might contain information about
distance in miles but you want to convert the information to kilometers. You can perform this
operation with:
>>> data = np.array([1.0, 2.0])
>>> data * 1.6
array([1.6, 3.2])
NumPy understands that the multiplication should happen with each cell. That concept is
called broadcasting. Broadcasting is a mechanism that allows NumPy to perform operations on
arrays of different shapes. The dimensions of your array must be compatible, for example, when
the dimensions of both arrays are equal or when one of them is 1. If the dimensions are not
compatible, you will get a ValueError.
Learn more about broadcasting here.
More useful array operations
This section covers maximum, minimum, sum, mean, product, standard deviation, and more
NumPy also performs aggregation functions. In addition to min, max, and sum, you can easily
run mean to get the average, prod to get the result of multiplying the elements together, std to get
the standard deviation, and more.
>>> data.max()
2.0
>>> data.min()
1.0
>>> data.sum()
3.0
Let’s start with this array, called “a”
>>> a = np.array([[0.45053314, 0.17296777, 0.34376245, 0.5510652],
...       [0.54627315, 0.05093587, 0.40067661, 0.55645993],
...       [0.12697628, 0.82485143, 0.26590556, 0.56917101]])
It’s very common to want to aggregate along a row or column. By default, every NumPy
aggregation function will return the aggregate of the entire array. To find the sum or the
minimum of the elements in your array, run:
>>> a.sum()
4.8595784
Or:
>>> a.min()
0.05093587
You can specify on which axis you want the aggregation function to be computed. For example,
you can find the minimum value within each column by specifying axis=0.
>>> a.min(axis=0)
array([0.12697628, 0.05093587, 0.26590556, 0.5510652 ])
The four values listed above correspond to the number of columns in your array. With a four-
column array, you will get four values as your result.
Read more about array methods here.
Creating matrices
You can pass Python lists of lists to create a 2-D array (or “matrix”) to represent them in NumPy.
>>> data = np.array([[1, 2], [3, 4], [5, 6]])
>>> data
array([[1, 2],
    [3, 4],
    [5, 6]])
Indexing and slicing operations are useful when you’re manipulating matrices:
>>> data[0, 1]
2
>>> data[1:3]
array([[3, 4],
    [5, 6]])
>>> data[0:2, 0]
array([1, 3])
You can aggregate matrices the same way you aggregated vectors:
>>> data.max()
6
>>> data.min()
1
>>> data.sum()
21
You can aggregate all the values in a matrix and you can aggregate them across columns or rows
using the axis parameter:
>>> data.max(axis=0)
array([5, 6])
>>> data.max(axis=1)
array([2, 4, 6])
Once you’ve created your matrices, you can add and multiply them using arithmetic operators if
you have two matrices that are the same size.
>>> data = np.array([[1, 2], [3, 4]])
>>> ones = np.array([[1, 1], [1, 1]])
>>> data + ones
array([[2, 3],
    [4, 5]])
You can do these arithmetic operations on matrices of different sizes, but only if one matrix has
only one column or one row. In this case, NumPy will use its broadcast rules for the operation.
>>> data = np.array([[1, 2], [3, 4], [5, 6]])
>>> ones_row = np.array([[1, 1]])
>>> data + ones_row
array([[2, 3],
    [4, 5],
    [6, 7]])
Be aware that when NumPy prints N-dimensional arrays, the last axis is looped over the fastest
while the first axis is the slowest. For instance:
>>> np.ones((4, 3, 2))
array([[[1., 1.],
     [1., 1.],
     [1., 1.]],
    [[1., 1.],
     [1., 1.],
     [1., 1.]],
    [[1., 1.],
     [1., 1.],
     [1., 1.]],
    [[1., 1.],
     [1., 1.],
     [1., 1.]]])
There are often instances where we want NumPy to initialize the values of an array. NumPy
offers functions like ones() and zeros(), and the random.Generator class for random number
generation for that. All you need to do is pass in the number of elements you want it to generate:
>>> np.ones(3)
array([1., 1., 1.])
>>> np.zeros(3)
array([0., 0., 0.])
# the simplest way to generate random numbers
>>> rng = np.random.default_rng(0)
>>> rng.random(3)
array([0.63696169, 0.26978671, 0.04097352])
You can also use ones(), zeros(), and random() to create a 2D array if you give them a tuple
describing the dimensions of the matrix:
>>> np.ones((3, 2))
array([[1., 1.],
    [1., 1.],
    [1., 1.]])
>>> np.zeros((3, 2))
array([[0., 0.],
    [0., 0.],
    [0., 0.]])
>>> rng.random((3, 2))
array([[0.01652764, 0.81327024],
    [0.91275558, 0.60663578],
    [0.72949656, 0.54362499]]) # may vary
Read more about creating arrays, filled with 0’s, 1’s, other values or uninitialized, at array
creation routines.
Task 1:
Task 1: create an array of numbers upto your roll number and then make it into
two arrays from its central element. And also Make it into three arrays
Task 2: add a number in a 1d and and 2d array
Task 3: add two different arrays
Task 4: find mean, average, median, minimum and maximum from an array of
numbers
Task 5: multiply an array with a non zero number
Procedure:
Results:
Conclusion: