Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

NumPy

NumPy stands for Numerical Python. It is a Python library used for working
with an array. In Python, we use the list for purpose of the array but it’s slow to
process. NumPy array is a powerful N-dimensional array object and its use in
linear algebra, Fourier transform, and random number capabilities. It provides
an array object much faster than traditional Python lists.

Types of Array:
One Dimensional Array
Multi-Dimensional Array
One Dimensional Array:
A one-dimensional array is a type of linear array.

# importing numpy module


Import numpy as np
# creating list
list = [1, 2, 3, 4]
# creating numpy array
sample_array = np.array(list1)
print("List in python : ", list)
print("Numpy Array in python :",sample_array)
OUTPUT:
List in python : [1, 2, 3, 4]
Numpy Array in python : [1 2 3 4]
Check data type for list and array:
print(type(list_1))
print(type(sample_array))
Output:

<class 'list'>
<class 'numpy.ndarray'>
Multi-Dimensional Array:
Data in multidimensional arrays are stored in tabular form.

# importing numpy module


import numpy as np
# creating list
list_1 = [1, 2, 3, 4]
list_2 = [5, 6, 7, 8]
list_3 = [9, 10, 11, 12]
# creating numpy array
sample_array = np.array([list_1,list_2,list_3])
print("Numpy multi dimensional array in python\n",sample_array)
Output:

Numpy multi dimensional array in python


[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
1. Axis: The Axis of an array describes the order of the indexing into the array.
Axis 0 = one dimensional
Axis 1 = Two dimensional
Axis 2 = Three dimensional
2. Shape: The number of elements along with each axis. It is from a tuple.
# importing numpy module
import numpy as np
# creating list
list_1 = [1, 2, 3, 4]
list_2 = [5, 6, 7, 8]
list_3 = [9, 10, 11, 12]
# creating numpy array
sample_array = np.array([list_1,list_2,list_3])
print("Numpy array :")
print(sample_array)
# print shape of the array
print("Shape of the array :",sample_array.shape)
Output:
Numpy array :
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
Shape of the array : (3, 4)
import numpy as np
sample_array = np.array([[0, 4, 2],[3, 4, 5],[23, 4, 5],[2, 34, 5],[5, 6, 7]])
print("shape of the array :",sample_array.shape)
Output:
shape of the array : (5, 3)
3. Rank: The rank of an array is simply the number of axes (or dimensions) it
has.

The one-dimensional array has rank 1.


The two-dimensional array has rank 2.
4. Data type objects (dtype): Data type objects (dtype) is an instance of
numpy.dtype class. It describes how the bytes in the fixed-size block of memory
corresponding to an array item should be interpreted.
# Import module
import numpy as np
# Creating the array
sample_array_1 = np.array([[0, 4, 2]])
sample_array_2 = np.array([0.2, 0.4, 2.4])
# display data type
print("Data type of the array 1 :",sample_array_1.dtype)
print("Data type of array 2 :",sample_array_2.dtype)
Output:
Data type of the array 1 : int32
Data type of array 2 : float64
Some different way of creating Numpy Array :
1. numpy.array(): The Numpy array object in Numpy is called ndarray. We can
create ndarray using numpy.array() function.
Syntax: numpy.array(parameter)
# import module
import numpy as np
#creating a array
arr = np.array([3,4,5,5])
print("Array :",arr)
Output:
Array : [3 4 5 5]
2. numpy.arange(): This is an inbuilt NumPy function that returns evenly spaced
values within a given interval.
Syntax: numpy.arange([start, ]stop, [step, ]dtype=None)
import numpy as np
np.arange(1, 20 , 2, dtype = np.float32)
output
array([ 1., 3., 5., 7., 9., 11., 13., 15., 17., 19.], dtype=float32)

3. numpy.linspace(): This function returns evenly spaced numbers over a


specified between two limits.
Syntax: numpy.linspace(start, stop, num=50, endpoint=True, retstep=False,
dtype=None, axis=0)

import numpy as np
np.linspace(3.5, 10, 3)
Output:
array([ 3.5 , 6.75, 10. ])
Python numpy Aggregate Functions
import numpy as np
arr1 = np.array([10, 20, 30, 40, 50])
print (arr1)
arr2 = np.array([[0, 10, 20], [30, 40, 50], [60, 70, 80]])
print(arr2)
arr3 = np.array([[[14, 6, 9, -12, 19, 72],[-9, 8, 22, 0, 99, -11]]])
print(arr3)
print("sum of array1",arr1.sum())
print("sum of array1",arr2.sum())
print("sum of array1",arr3.sum())
print("sum of one dimension",arr1.sum(axis=0))
print("sum of two dimension",arr2.sum(axis=1))
print("sum of three dimension",arr3.sum(axis=2))
OUTPUT
Array 1 [10 20 30 40 50]
Array 2 [[ 0 10 20]
[30 40 50]
[60 70 80]]
Array 3 [[[ 14 6 9 -12 19 72]
[ -9 8 22 0 99 -11]]]
sum of array1 150
sum of array1 360
sum of array1 217
sum of one dimension 150
sum of two dimension [ 30 120 210]
sum of three dimension [[108 109]]
#Finding average
np.average(arr1)
np.average(arr2)
np.average(arr3)

30.0
40.0
18.083333333333332

#Python numpy min


The Python numpy min function returns the minimum value in an array or a
given axis.

arr1.min()
arr2.min()
arr3.min()
OUTPUT
10
0
-12

Python numpy max


arr1.max()
arr2.max()
arr3.max()

Python numpy median

np.median(arr1)
np.median(arr2)
np.median(arr3)
output
Median= 30.0
Median= 40.0
Median= 8.5

Python numpy var function


The Python numpy var function returns the variance of a given array or in a
given axis. The formula for this Python numpy var is : (item1 – mean)2 + …
(itemN – mean)2 / total items
print("Variance: ",arr1.var())
print("Variance: ",arr2.var())
print("Variance: ",arr3.var())
output
Variance: 200.0
Variance: 666.6666666666666
Variance: 1052.4097222222224

Python numpy cumsum


The Python numpy cumsum function returns the cumulative sum of a given
array or in a given axis.
arr1.cumsum()
arr2.cumsum()
arr3.cumsum()
output
Cumulative Sum : [ 10 30 60 100 150]
Cumulative Sum : [ 0 10 30 60 100 150 210 280 360]
Cumulative Sum : [ 14 20 29 17 36 108 99 107 129 129 228 217]

The add() function sums the content of two arrays, and return the results in a
new array.
import numpy as np
arr1 = np.array([10, 11, 12, 13, 14, 15])
arr2 = np.array([20, 21, 22, 23, 24, 25])
newarr = np.add(arr1, arr2)
print(newarr)
OUTPUT: [30 32 34 36 38 40]

The subtract() function subtracts the values from one array with the values from
another array, and return the results in a new array.
import numpy as np
arr1 = np.array([10, 20, 30, 40, 50, 60])
arr2 = np.array([20, 21, 22, 23, 24, 25])
newarr = np.subtract(arr1, arr2)
print(newarr)
OUTPUT: [-10 -1 8 17 26 35]
The multiply() function multiplies the values from one array with the values
from another array, and return the results in a new array.
import numpy as np
arr1 = np.array([10, 20, 30, 40, 50, 60])
arr2 = np.array([20, 21, 22, 23, 24, 25])
newarr = np.multiply(arr1, arr2)
print(newarr)
OUTPUT: [ 200 420 660 920 1200 1500]

The divide() function divides the values from one array with the values from
another array, and return the results in a new array.
import numpy as np
arr1 = np.array([10, 20, 30, 40, 50, 60])
arr2 = np.array([3, 5, 10, 8, 2, 33])
newarr = np.divide(arr1, arr2)
print(newarr)
OUTPUT: [ 3.33333333 4. 3. 5. 25. 1.81818182]
Both the absolute() and the abs() functions do the same absolute operation
element-wise but we should use absolute() to avoid confusion with python's
inbuilt math.abs()
import numpy as np
arr = np.array([-1, -2, 1, 2, 3, -4])
newarr = np.absolute(arr)
print(newarr)
OUTPUT: [1 2 1 2 3 4]
The divmod() function return both the quotient and the the mod. The return
value is two arrays, the first array contains the quotient and second array
contains the mod.
import numpy as np
arr1 = np.array([10, 20, 30, 40, 50, 60])
arr2 = np.array([3, 7, 9, 8, 2, 33])
newarr = np.divmod(arr1, arr2)
print(newarr)
OUTPUT: (array([ 3, 2, 3, 5, 25, 1]), array([ 1, 6, 3, 0, 0, 27]))

Both the mod() and the remainder() functions return the remainder of the values
in the first array corresponding to the values in the second array, and return the
results in a new array.
import numpy as np
arr1 = np.array([10, 20, 30, 40, 50, 60])
arr2 = np.array([3, 7, 9, 8, 2, 33])
newarr = np.mod(arr1, arr2)
print(newarr)
OUTPUT: [ 1 6 3 0 0 27]
The power() function rises the values from the first array to the power of the
values of the second array, and return the results in a new array.
import numpy as np
arr1 = np.array([10, 20, 30, 40, 50, 60])
arr2 = np.array([3, 5, 6, 8, 2, 33])
newarr = np.power(arr1, arr2)
print(newarr)
OUTPUT : [ 1000 3200000 729000000 6553600000000 2500 0]

NumPy Fancy Indexing


In NumPy, fancy indexing allows us to use an array of indices to access
multiple array elements at once.

Fancy indexing can perform more advanced and efficient array operations,
including conditional filtering, sorting, and so on.
Select Multiple Elements Using NumPy Fancy Indexing
import numpy as np
# create a numpy array
array1 = np.array([1, 2, 3, 4, 5, 6, 7, 8])
# select elements at index 1, 2, 5, 7
select_elements = array1[[1, 2, 5, 7]]
print(select_elements)
Output: [2 3 6 8]
NumPy Fancy Indexing
import numpy as np
array1 = np.array([1, 2, 3, 4, 5, 6, 7, 8])
# select a single element
simple_indexing = array1[3]
print("Simple Indexing:",simple_indexing) # 4
# select multiple elements
fancy_indexing = array1[[1, 2, 5, 7]]
print("Fancy Indexing:",fancy_indexing) # [2 3 6 8]
OUTPUT
Simple Indexing: 4
Fancy Indexing: [2 3 6 8]

Fancy Indexing for Sorting NumPy Array


Fancy indexing can also sort a NumPy array.
import numpy as np
array1 = np.array([3, 2, 6, 1, 8, 5, 7, 4])
# sort array1 using fancy indexing
sorted_array = array1[np.argsort(array1)]
print(sorted_array)
Output: [1, 2, 3, 4, 5, 6, 7, 8]
use fancy indexing to sort the array in descending order.
import numpy as np
array1 = np.array([3, 2, 6, 1, 8, 5, 7, 4])
# sort array1 using fancy indexing in descending order
sorted_array = array1[np.argsort(-array1)]
print(sorted_array)
Output: [8 7 6 5 4 3 2 1]

Fancy Indexing on N-d Arrays


import numpy as np
# create a 2D array
array1 = np.array([[1, 3, 5], [11, 7, 9], [13, 18, 29]])
# create an array of row indices
row_indices = np.array([0, 2])
# use fancy indexing to select specific rows
selected_rows = array1[row_indices, :]
print(selected_rows)
OUTPUT:
[[ 1 3 5]
[13 18 29]]

Python: Numpy’s Structured Array

Numpy’s Structured Array is similar to Struct in C. It is used for grouping data


of different types and sizes. Structure array uses data containers called fields.
Each data field can contain data of any type and size. Array elements can be
accessed with the help of dot notation.
Note: Arrays with named fields that can contain data of various types and sizes.
Properties of Structured array
All structs in array have same number of fields.
All structs have same fields names.
# Python program to demonstrate
# Structured array
import numpy as np
a = np.array([('Sana', 2, 21.0), ('Mansi', 7, 29.0)], dtype=[('name', (np.str_, 10)),
('age', np.int32), ('weight', np.float64)])
print(a)
Output:
[('Sana', 2, 21.0) ('Mansi', 7, 29.0)]

Example 2: The structure array can be sorted by using numpy.sort() method and
passing the order as parameter. This parameter takes the value of the field
according to which it is needed to be sorted.
# Python program to demonstrate
# Structured array
import numpy as np
a = np.array([('Sana', 2, 21.0), ('Mansi', 7, 29.0)], dtype=[('name', (np.str_, 10)),
('age', np.int32), ('weight', np.float64)])
# Sorting according to the name
b = np.sort(a, order='name')
print('Sorting according to the name', b)
# Sorting according to the age
b = np.sort(a, order='age')
print('\nSorting according to the age', b)
Output:
Sorting according to the name [('Mansi', 7, 29.0) ('Sana', 2, 21.0)]
Sorting according to the age [('Sana', 2, 21.0) ('Mansi', 7, 29.0)]

You might also like