It stands for Numerical Python, and is a general-purpose array-processing python package. NumPy helps to create arrays, with the help of bindings of C++. Therefore, it is quite fast. It is the fundamental package for scientific computing with Python.

The NumPy library also contains a multidimensional array and matrix data structures. It is one of the very important libraries used in the field of Data Science & Machine Learning.

Why do we need NumPy ?

Why do we need a NumPy array when we have python lists?
NumPy aims to provide an array object that is up to 50x faster than Python lists. We can perform operations on all the elements of a NumPy array at once, which are not possible with python lists.
NumPy ndarray provides a lot of supporting functions that make working with ndarray very easy. Arrays are very frequently used in data science, where speed and resources are very important.

Arrays in Numpy

Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the array.A tuple of integers giving the size of the array along each dimension is known as shape of the array. An array class in Numpy is called as ndarray. Elements in Numpy arrays are accessed by using square brackets and can be initialized by using nested Python Lists.
Accessing the array Index
In a numpy array, indexing or accessing the array index can be done in multiple ways. To print a range of an array, slicing is done. Slicing of an array is defining a range in a new array which is used to print a range of elements from the original array. Since, sliced array holds a range of elements of the original array, modifying content with the help of sliced array modifies the original array content.

Data Types in Numpy

Every Numpy array is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. Every ndarray has an associated data type (dtype) object. This data type object (dtype) provides information about the layout of the array. The values of an ndarray are stored in a buffer which can be thought of as a contiguous block of memory bytes which can be interpreted by the dtype object. Numpy provides a large set of numeric datatypes that can be used to construct arrays. At the time of Array creation, Numpy tries to guess a datatype, but functions that construct arrays usually also include an optional argument to explicitly specify the datatype.

Constructing a Datatype Object

In Numpy, datatypes of Arrays need not to be defined unless a specific datatype is required. Numpy tries to guess the datatype for Arrays which are not predefined in the constructor function.

Installing NumPy in Python

If you use pip, you can install it with

pip install numpy

If you use conda, you can install it with

conda install numpy
import numpy as np
array = np.array([
    [1, 2, 3, 5, 6],
    [2, 1, 5, 6, 7]])
print("No. of dimensions of the array: ", array.ndim)

Output: No. of dimensions of the array: 2

print("Shape of the array: ", array.shape)
Output: Shape of the array: (2, 5)

print("Size of the array: ", array.size)
Output: Size of the array: 10

Creating a NumPy Array

Arrays in NumPy can be created in multiple ways, with various number of Ranks, defining the size of the Array. Arrays can also be created with the use of various data types such as lists, tuples.

#Creating a rank 1 array by passing one python list

import numpy as np
list = [1, 2, 3, 5, 6]
array = np.array(list)
print(array)
Output: [1 2 3 5 6]

#Creating a rank 2 array by passing two python lists

list1 = [1, 2, 3, 5, 6]
list2 = [3, 1, 4, 5, 1]
array = np.array([list1, list2])
print(array)
Output: [[1 2 3 5 6][3 1 4 5 1]]

#Creating array by passing a python tuple
tuple = (1, 2, 3, 5, 6)
array = np.array(tuple)
print(array)
Output: [1 2 3 5 6]

#Creating a 3×4 array with all zeros
array = np.zeros((3, 4))
print(array)
Output:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]

#Creating a constant value array of complex type
array = np.full((3, 3), 6, dtype='complex')
print(array)
Output:
[[6.+0.j 6.+0.j 6.+0.j]
[6.+0.j 6.+0.j 6.+0.j]
[6.+0.j 6.+0.j 6.+0.j]]

NumPy Array Indexing

Indexing can be done in NumPy by using an array as an index.
Note, the first element is indexed by 0 second first by 1 and so on, whereas the last element is indexed by -1 second last by -2 and so on.

#Creating array by passing one python list
list = [1, 2, 3, 5, 6]
array = np.array(list)
print(array)
Output: [1 2 3 5 6]

#Accessing elements and creating new array by passing indices
newArray = array[np.array([2, 0, 1, 4])]
print(newArray)
Output: [3 1 2 6]

#Index values can be negative
newArray = array[np.array([2, 0, -1, -4])]
print(newArray)
Output: [3 1 6 2]

NumPy String Operations

#Returns the uppercased string from the given string.

import numpy as np
string = "devopscube"
print(np.char.upper(string))
Output: DEVOPSCUBE

#similary one can use numpy.lower( ) to convert all uppercase characters to lowercase.

#Returns a list of strings after breaking the given string by the specified separator.

string = "devopscube.com"
print(np.char.split(string, sep='.'))
Output: ['devopscube', 'com']

#It is used to convert the first character in each word to Uppercase.

string = "devopsCube is An amaZing pOrtal"
print(np.char.title(string))
Output: Devopscube Is An Amazing Portal

#This function checks for string1 == string2 elementwise and return a boolean value true or false.

string1 = "Devopscube"
string2 = "Devopscube.com"
print(np.char.equal(string1, string2))
Output: False

NumPy Mathematical Functions

#This mathematical function helps the user to calculate trigono metrics for given values.

x = 0
print(np.sin(x))

x = np.pi / 2
print(np.sin(x))

x = np.pi / 4
print(np.sin(x))
Output:
0.0
1.0
0.7071067811865475

#Similarly one can use numpy.cos( ), numpy.tan( ), numpy.arcsin( ), numpy.arccos( ), numpy.arctan( ) to calculate trignometric cosine (cos), tangent (tan), cosecant (csc), secant (sec), and cotangent (cot) respectively for given values.
#This mathematical function round an array to the given number of decimals.

arr = [.33345, .1234, 1.456789]
roundOffValues = np.round_(arr, decimals=3)
print(roundOffValues)
Output: [0.333 0.123 1.457]

#This mathematical function helps users to calculate Natural logarithm of all elements in the input array.

arr = [1, 3, 50]
logValues = np.log(arr)
print(logValues)
Output: [0. 1.09861229 3.91202301]

#This mathematical function helps users to calculate the exponential of all elements in the input array.

arr = [1, 3, 50]
expValues = np.exp(arr)
print(expValues)
Output: [2.71828183e+00 2.00855369e+01 5.18470553e+21]

NumPy Cheat Sheet

Recommended for you:

Numpy cheat sheet
NumPy: the absolute basics for beginners

Leave a Reply

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

Numpy Cheat Sheet

November 24, 2022

K-Nearest Neighbors Algorithm

November 29, 2022