Python Programming - Introduction To Numpy

You can learn about NumPy in Python Programs with Outputs helped you to understand the language better.

Python Programming – Introduction To Numpy

NumPy stands for ‘Numerical Python’ or ‘Numeric Python’. It is an open-source module of Python which provides fast mathematical computation on arrays and matrices. Since arrays and matrices are an essential part of the Machine Learning ecosystem, NumPy along with Machine Learning modules like Scikit-learn, Pandas, Matplotlib, TensorFlow, etc., complete the Python Machine Learning Ecosystem. NumPy is also useful in linear algebra, random number capability etc.
In order to use Numpy, you must import in your module by using a statement like:
import numpy as np
The above statement has given np as alias name for numpy module. Once imported you can use both names i.e., numpy or np for functions, e.g. num- py.array( ) is same as np.array( ).

Arrays, in general, refer to a named group of homogeneous (of the same type) elements. For example, students array containing 5 entries as [84, 87, 63, 74, 52] then students is an array. Each item stored in an array is called an element. Each location of an element in an array has a numerical index, which is used to identify the element. Numpy refers to the dimensions of its arrays as axes. Axes are always numbered 0 onwards. The shape of an array depends upon the list of integers giving the size of the array along each dimension.
A NumPy array is simply a grid that contains values of the same/homogeneous type. NumPy Arrays come in two forms:

(a) l-D(one-dimensional) arrays known as Vectors(having single row/column only). To create a one-dimensional NumPy array, you can simply pass a Python list to the array method. For example,
# Creating a 1-D Numpy array
import NumPy as np
x = [2,4,6,81
nums=np.array(x)
print(nuns)

>>>
[2, 4 , 6, 8]
>>>
In the script above you first imported the NumPy library as np, and created a list x. We then passed this list to the array function of the NumPy library. Finally, you printed the nums array on the screen.

(b) Multidimensional arrays known as Matrices(can have multiple rows and columns). For example,
# Creating a 2-D Numpy array
import numpy as np
nums = np.array([ [1,2,3,4] ,
[11.12.13.14] ])
print(nums[1,3])
print(nums[1][3])
print(nums)

>>>
14
14
[[ 11,2,3,4]
[11.12.13.14]]
>>>
The above script results in a matrix where every inner list in the outer list becomes a row. The number of columns is equal to the number of elements in each inner list.
Individual elements of array can be accessed using arrayname [index] and multi-dimension arrays can be accessed as arrayname[row][col] or arrayna- me[row,col].

Python Programming - Introduction To Numpy chapter 13 img 1

ndarray

NumPy works with Python objects called multi-dimensional arrays. Arrays are basically collections of values, and they have one or more dimensions. NumPy array data structure is also called ndarray, short for the n-dimensional array. It is also known as the alias array. An array with one dimension is called a vector and an array with two dimensions is called a! matrix.
NumPy’s main object is the homogeneous multidimensional array. It is a table of elements (usually numbers), all of the same type, indexed by positive integers. In NumPy, dimensions are called axes. The number of axes is rank.
For example, the coordinates of a point in 3D space [1, 2, 1] have one axis. That axis has 3 elements in it, so you can say it has a length of 3. In the example given below, the array has 2 axes. The first axis has a length of 2, the second axis has a length of 3.
[[ 1., 0., 0.] ,
[ 0. , 1., 2.] ]

Difference between NumPy Array and List

  • Once a Numpy array is created, you cannot change its size, However, size can be changed in the list.
  • NumPy array contains elements of homoge- neous(same) types. Python list contains ele-ments of heterogeneous(different) types.
  • Numpy array occupies much less space and memory consumption than a Python list.

Datatypes

A data type describes what type of data is to be stored in a variable, or in any Python object. A data type object is an instance of NumPy.type class which describes how the bytes in the fixed-size block of memory corresponding to an array item should be interpreted, types can be referenced by their class, long name, or short name. It describes the following aspects of the data:

  • Type of the data such as integer, float, Python object, etc.
  • Size of the data which lists the size (in bytes) of each array element.
  • The byte order of the data.

NumPy supports a much greater variety of numerical types. There are 5 basic numerical types representing booleans (bool), integers (int), unsigned integers (uint), floating-point (float), and complex. Those with numbers in their name indicate the bit- size of the type (Number of bits needed to represent a single value in memory). One bit can hold the value 0 or 1, and computers organize memory in units of bytes, which are 8 bits, allowing for 28 = 256 different values per byte. Along with the above numerical types, it also supports strings (str, Unicode), object, which represents items in the array as Python objects and records, use for arbitrary data structures in record arrays.

Array from exiting data

an array is created from exiting data by the following functions.
numpy. asarray
this array is used from converting the python sequence into array. this routine is used to create an array by using the existing data in the form of lists, or tuples.
numpy.asarray(sequence, dtype = None,
order = None)
It accepts the following parameters.
(a) sequence: It is the Python sequence that is to be converted into the Python array. Input data can be in any form such as list, list of tuples, tuples, a tuple of tuples, or tuple of lists.
(b) dtype: It is the data type of each item of the array.
(c) order: It can be set to C (row-major) or F (column-major). The default is C.

Example
program to convert list to ndarray.

# Convert list to ndarray
import numpy as np
x = [1,2,3]
a = np.asarray(x)
print(type(a))
print(a)RUN
>>>
<class ‘numpy.ndarray’>
[1 2 3]
>>>

Example
Program to Create a numpy array using Tuple.

#Creating a numpy array using Tuple
import numpy as np
1=(1,2,3,4,5,6,7)
a = np.asarray(1);
print(type(a))
print(a)RUN
>>>
<class ‘numpy.ndarray’>
[1 2 3 4 5 6 7]
>>>

Let’s Try

# Creating numpy array using the list
import numpy as np
1=[1,2,3,4,5,6,7]
a = np.asarray(1);
print(type(a))
print(a)

Joining and Splitting

Joining(concatenation) of arrays means combining multiple arrays into one and splitting of arrays means splitting one array into many. Concatenation, or joining of two arrays in NumPy, is primarily accomplished using the routines np. concatenate, np.vstack, and np.hstack. np. concatenate takes a tuple or list of arrays as its first argument.

Example
Demo of concatenation.

# Concatenation
import numpy as np
x = np.array([1, 2, 3])
y = np.array([5, 6, 7])
z=np.concatenate([x, y])
print(z)RUN
>>>
[1 2 3 5 6 7]
>>>

You can also concatenate more than two arrays at once. In addition to the concatenation function, Numpy also offers two convenient functions hstack(horizontal stack) and vstack(vertical stack) which allows you to concatenate two multi-dimensional arrays vertically or horizontally. (See Figure 13.24).

Example
Demo of vstack and hstack functions.

import numpy as np
a = np.array([[1,2,30], [10,15,4]])
b = np.array([[1,2,3], 112, 19, 29]])
print(“Arrays vertically concatenated\n”,np.vstack((a,b)))
print(“Arrays horizontally concatenated\n”,np.hstack((a,b)))RUN
>>>
Arrays vertically concatenated
[ [ 1 2 30]
[10 15 4]
[12 3]
[12 19 29] ]
Arrays horizontally concatenated
[ [ 1 2 30 1 2 3]
[1015 4 12 19 29]]
>>>

Let’s Try

import numpy as np
a = np.array([[1,2,3],[11,12,13]])
b = np.array([[4,5,6], [14, 15, 16]])
print(“Arrays vertically concatenated\n”,np.vstack((a,b)))
print(“Arrays horizontally concatenated\n”,np.hstack((a,b)))

The opposite of concatenation is splitting, i.e., to split a single array into multiple arrays which are implemented by the functions np.split, np.hsplit,and np.vsplit. For each of these, you can pass a list of indices giving the split points. (See Figure 13.25).

Example
Demo of Splitting.

# Splitting
import numpy as np
x = [1, 2, 3 , 99, 99, 3, 2, 1]
xl, x2. x3 = np.split (x. [3, 5])
print(x1 , x2 , x3)RUN
>>>
[1 2 3] [99 99] [3 2 1]
>>>

Let’s Try

# Splitting
import numpy as np
x = [1, 2, 3, 4, 5, 6, 7, 8]
xl, x2, x3 = np.split(x. [2, 4])
print(x1 , x2, x3)

Arithmetic Operations on Array

NumPy is not only about efficient storing of data but also makes it extremely easy to perform the arithmetic operations on multi-dimensional arrays directly. In the following example, the arithmetic operations are performed on the two multi-dimensional arrays, of arithmetic operations.

Example
Demo of arithmetic operations.

import numpy as np
a = np.array([[10,20,30], [10,15,4]])
b = np.array![[2,4,8] , [5, 19, 29]])
print(“Sum of array a and b\n”,a+b)
print(“Product of array a and b\n”,a*b)
print(“Division of array a and b\n”,a/b)RUN
>>>
Sum of array a and b
[[12 24 38]
[15 34 33]]
Product of array a and b
[[ 20 80 240]
[ 50 285 116]]
Division of array a and b
[ [5. 5 . 3.75 ]
[2. 0.78947368 0.13793103]]
>>>

Let’s Try

import numpy as np
x = np. array ( [ [12,16,15] , [10,15,4] ] )
y = np.array( [ [2,4,5], [5, 3, 2]])
print(“Sum of array\n”,x+y)
print(“Product of array \n”,x*y)
print(“Division of array\n”,x/y)

Leave a Reply

Your email address will not be published. Required fields are marked *