What is NumPy?
NumPy is a powerful library in python numerical computing.it provides high-performance multidimensional array object and functions for working with this arrays With numpy you can perform mathematical and logical operations on arrays manipulate array shapes and perform various array operations efficiently.
Feature of Numpy
Why do we import NumPy?
Working with NumPy entails importing the NumPy module before you start writing the code.
When we import NumPy as np
, we establish a link with NumPy. We are also shortening the word “numpy” to “np” to make our code easier to read and help avoid namespace issues.
python
import numpy as np
The above is the same as the below:
python
import numpy
np = numpy
del numpy
NumPy arrays by dimensions
NumPy Creating Arrays
Creating an Array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
Output:
[1 2 3 4 5]
Dimensions- Arrays:
0-D Arrays:
The following code will create a zero-dimensional array with a value 36.
import numpy as np
arr = np.array(36)
print(arr)
Output:
36
1-Dimensional Array:
The array that has Zero Dimensional arrays as its elements is a uni-dimensional or 1-D array.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
Output:
[1 2 3 4 5]
Two Dimensional Arrays:
2-D Arrays are the ones that have 1-D arrays as its element. The following code will create a 2-D array with 1,2,3 and 4,5,6 as its values.
import numpy as np
3
arr1 = np.array([[1, 2, 3], [4, 5, 6]])
print(arr1)
Output:
[[1 2 3]
[4 5 6]]
Three Dimensional Arrays:
Let us see an example of creating a 3-D array with two 2-D arrays:
import numpy as np
arr1 = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]]) print(arr1)
Output:
[[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]]
What are vectors and matrices?
A vector is an array of one dimension. We have a single vector when our dataset is meant to take a single column of input and is expected to make predictions from it.
A matrix is a two-dimensional data structure where numbers are arranged into rows and columns. For example:
Creating a NumPy array from a Python list
The code snippet below depicts how to call NumPy’s inbuilt method (array) on a Python list of integers to form a NumPy array object.
python
import numpy as np
ones_array = np.ones(6, dtype = int)
ones_array
We can alternative create a matrix of it:
python
import numpy as np
arr = np.ones(6, dtype = int).reshape(3,2)
arr
Important Numpy Functions in Python:
- np.array(): This function is used to create an array in NumPy.
ex: Import numpy as np
import numpy as np
2. zeros(): It create n-dimentional array, all the elements sholud be 0 (zero).
3.Ones(): It create n-dimentional array, all the elements sholud be 1 (one).
4.Full(): The numpy. full() function is used to return a new array of a given shape and data type filled with fill_value .
5.Eye(): eye() function in Python is used to return a two-dimensional array with ones (1) on the diagonal and zeros (0) elsewhere.
6.Arrange(): The numpy. arange() function is used to generate an array with evenly spaced values within a specified interval. The function returns a one-dimensional array of type numpy.
7.Diag():Numpy diag()function is used to extract or construct a diagonal 2-d array.
8.linspace(): linspace is an in-built function in Python’s NumPy library. It is used to create an evenly spaced sequence in a specified interval.
9.random.random():It returns an array of specified shape and fills it with random floats in the half-open interval [0.0, 1.0).
10. random.rand(): The numpy.random.rand() function creates an array of specified shape and fills it with random values.
11. random.randint(): The numpy.random.randint() method in Python returns a random integer value between the two lower and higher limits (including both limits) provided as two parameters.
12. random.choice(): The choice() method returns a randomly selected element from the specified sequence. The sequence can be a string, a range, a list, a tuple or any other kind of sequence.
Reshaping an array
Reshaping a ndarray can be done using the np.reshape() method. It changes the shape of the ndarray without changing the data within the ndarray:
# reshape
a = np.array([3,6,9,12])
np.reshape(a,(2,2))
array([[ 3, 6],
[ 9, 12]])
Reshaping a vector to a matrix
python
import numpy as np
a = np.arrange(12)
matrix = a.reshape(3,4)
print(matrix)
Adding more rows and columns
The code snippet below starts with a one-dimensional array of nine elements, but we reshape it to two dimensions, with three rows and three columns.
python
import numpy as np
one_d_array = np.array([2,3,4,5,6,7,8,9,10])
reshaped_array = one_d_array.reshape(3,3)
reshaped_array
Flattening a NumPy array
>> import numpy as np
>>>y = np.array([[2,3], [4,5]])
>>> y.flatten() array([2, 3, 4, 5])
Size of NumPy array
You can determine how many values there are in the array using the size attribute. It just multiplies the number of rows by the number of columns in the ndarray:
Accessing the elements in 2-dimensional:
Three types of Accessing elements
- slicing based Accessing: Extracting a specific portion of sequence.
- syntax:[start:end:step]
slicing works on:
- string
- tuple
- array
- list
properties:
- sequence of element.
- Always sub-array having same rank doesn’t effect original array.
2. Integer based Accessing: It access the elements row wise and column wise.
properties:
- sub array always be in lower than parent.
- It can access any arbitary points.
- sub array is the copy of the original array.
3. Boolean Based Accessing: Whenever we want to access the elements based on the condition.Boolean means a binary variables that can represent two states True or False.
properties of Boolean Based indexing:
- The rank will not be same.
- Sub array is a copy of original array.
Different functions for doing manipulation on array:
- reshape(): The numpy.reshape() function is used to change the shape (dimensions) of an array without changing its data. This function returns a new array with the same data but with a different shape.
2. dot(): numpy.dot(vector_a, vector_b, out = None) returns the dot product of vectors a and b. It can handle 2D arrays but considers them as matrix and will perform matrix multiplication. For N dimensions it is a sum-product over the last axis of a and the second-to-last of b : dot(a, b).
3.Logical operations on Arrays
- logical_or(): logical_or() method is used to calculate truth values between x1 and x2 element-wise. The logical OR returns true, when at least one input is true. logical or() operation performs element wise
2.logical_and(): The && (logical AND) operator indicates whether both operands are true. If both operands have nonzero values, the result has the value 1 . Otherwise, the result has the value 0 . The type of the result is int .
4. all(): The all() function returns True if all items in an iterable are true, otherwise it returns False. If the iterable object is empty, the all() function also returns True.
5. any(): The any() function returns True if any item in an iterable are true, otherwise it returns False. If the iterable object is empty, the any() function will return False.
6. array_equal(): array_equal(arr1, arr2) : This logical function that checks if two arrays have the same shape and elements.
7. copy(): Whenever we want to create a copy of an array it effects copied array and original array will not be effected.
8. view(): Whenever we want to create a viewof an array it effects both view array and original array .
9.ravel(): ravel() function is used to create a contiguous flattened array. A 1-D array, containing the elements of the input, is returned. A copy is made only if needed.
10. Flatten(): flatten() method in Python is used to return a copy of a given array in such a way that it is collapsed into one dimension.
11.np.sum(): It will take all the elements inside the array and perform addition.
12. np.product(): It will take all the elements inside the array and perform multiplication.
13. np.nansum(): nansum() function is used when we want to compute the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.
14. np.cumsum(): The cumsum() method returns a DataFrame with the cumulative sum for each row. The cumsum() method goes through the values in the DataFrame, from the top, row by row, adding the values with the value from the previous row, ending up with a DataFrame where the last row contains the sum of all values for each column.
15. np.nancumsum(): nancumsum() function is used when we want to compute the cumulative sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.
16.np.cumprod(): cumprod() function is used when we want to compute the cumulative product of array elements over a given axis.
17. np.nancumprod():Return the cumulative product of array elements over a given axis treating Not a Numbers (NaNs) as one.
18. np.round(): The round() function returns floating-point elements of an array to the nearest integer or rounded to the specified number of decimals.
19. np.floor(): It round off to the previous whole numbers.
20. np.ceil(): It round offto the next whole numbers.
21. np.repeat(): Whenever we want to repeat the elements n-times in an array repeat() is used.
22. np.tile(): Whenever we want to repeat entire array ’n’ no.of times tile() is used.
23. np.unique(): The numpy. unique() function finds the unique elements of an array and returns these unique elements as a sorted array.
24.max(): MAX will return the largest value in a given list of arguments. From a given set of numeric values, it will return the highest value.
25.min(): MIN will return the lowest value in a given list of arguments. From a given set of numeric values, it will return the lowest value.
Combining rows and columns:
- concatenation: To combine Multiple array into single array then concatination technique is used.
2. hstack(): hstack() function is used to stack the sequence of input arrays horizontally (i.e. column wise) to make a single array.
3. vstack(): vstack() function is used to stack the sequence of input arrays vertically to make a single array.
Sorting the arrays:
- sort(): The sort function can be used to sort the list in both ascending and descending order.
2. lexsort(): lexsort(keys, axis=-1) Perform an indirect stable sort using a sequence of keys. Given multiple sorting keys, which can be interpreted as columns in a spreadsheet, lexsort returns an array of integer indices that describes the sort order by multiple columns.