NumPy is an open-source Python library that provides support for large, multi-dimensional arrays and matrices. It also have a collection of high-level mathematical functions to operate on arrays.
Features of NumPy
NumPy has various features which make them popular over lists.
- Provides powerful, multidimensional array objects (ndarrays).
- Supports advanced slicing and indexing techniques.
- Reduces the need for explicit loops with efficient array operations.
- Easily integrates with other libraries like pandas, matplotlib, and SciPy.
- Useful linear algebra, Fourier transform, and random number capabilities
Arbitrary data types can be defined using Numpy which allows NumPy to seamlessly and speedily integrate with a wide variety of databases.
Install Python NumPy
Numpy can be installed for Mac and Linux users via the following pip command:
pip install numpy
Windows does not have any package manager analogous to that in Linux or Mac.
Arrays in NumPy
NumPyâs main object is the homogeneous multidimensional array.
- It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers.
- In NumPy, dimensions are called axes. The number of axes is rank.
- NumPyâs array class is called ndarray. It is also known by the alias array.
Example:
In this example, we are creating a two-dimensional array that has the rank of 2 as it has 2 axes.
The first axis(dimension) is of length 2, i.e., the number of rows, and the second axis(dimension) is of length 3, i.e., the number of columns. The overall shape of the array can be represented as (2, 3)
Python
import numpy as np
# Creating array object
arr = np.array( [[ 1, 2, 3],
[ 4, 2, 5]] )
# Printing type of arr object
print("Array is of type: ", type(arr))
# Printing array dimensions (axes)
print("No. of dimensions: ", arr.ndim)
# Printing shape of array
print("Shape of array: ", arr.shape)
# Printing size (total number of elements) of array
print("Size of array: ", arr.size)
# Printing type of elements in array
print("Array stores elements of type: ", arr.dtype)
Output:
Array is of type: <class 'numpy.ndarray'>
No. of dimensions: 2
Shape of array: (2, 3)
Size of array: 6
Array stores elements of type: int64
NumPy Array Creation
There are various ways of Numpy array creation in Python. They are as follows:
1. Create NumPy Array with List and Tuple
You can create an array from a regular Python list or tuple using the array() function. The type of the resulting array is deduced from the type of the elements in the sequences. Let’s see this implementation:
Python
import numpy as np
# Creating array from list with type float
a = np.array([[1, 2, 4], [5, 8, 7]], dtype = 'float')
print ("Array created using passed list:\n", a)
# Creating array from tuple
b = np.array((1 , 3, 2))
print ("\nArray created using passed tuple:\n", b)
Output:
Array created using passed list:
[[1. 2. 4.]
[5. 8. 7.]]
Array created using passed tuple:
[1 3 2]
2. Create Array of Fixed Size
Often, the element is of an array is originally unknown, but its size is known. Hence, NumPy offers several functions to create arrays with initial placeholder content.
This minimize the necessity of growing arrays, an expensive operation. For example: np.zeros, np.ones, np.full, np.empty, etc.
To create sequences of numbers, NumPy provides a function analogous to the range that returns arrays instead of lists.
Python
# Creating a 3X4 array with all zeros
c = np.zeros((3, 4))
print ("An array initialized with all zeros:\n", c)
# Create a constant value array of complex type
d = np.full((3, 3), 6, dtype = 'complex')
print ("An array initialized with all 6s."
"Array type is complex:\n", d)
# Create an array with random values
e = np.random.random((2, 2))
print ("A random array:\n", e)
Output:
An array initialized with all zeros:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
An array initialized with all 6s.Array type is complex:
[[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]]
A random array:
[[0.15471821 0.47506745]
[0.03637972 0.15772238]]
3. Create Using arange() Function
arange(): This function returns evenly spaced values within a given interval. Step size is specified.
Python
# Create a sequence of integers
# from 0 to 30 with steps of 5
f = np.arange(0, 30, 5)
print ("A sequential array with steps of 5:\n", f)
Output:
A sequential array with steps of 5:
[ 0 5 10 15 20 25]
5. Create Using linspace() Function
linspace(): It returns evenly spaced values within a given interval.
Python
# Create a sequence of 10 values in range 0 to 5
g = np.linspace(0, 5, 10)
print ("A sequential array with 10 values between"
"0 and 5:\n", g)
Output:
A sequential array with 10 values between0 and 5:
[0. 0.55555556 1.11111111 1.66666667 2.22222222 2.77777778
3.33333333 3.88888889 4.44444444 5. ]
6. Reshaping Array using Reshape Method
Reshaping array: We can use reshape method to reshape an array.
Consider an array with shape (a1, a2, a3, âĶ, aN). We can reshape and convert it into another array with shape (b1, b2, b3, âĶ, bM). The only required condition is a1 x a2 x a3 âĶ x aN = b1 x b2 x b3 âĶ x bM. (i.e. the original size of the array remains unchanged.)
Python
# Reshaping 3X4 array to 2X2X3 array
arr = np.array([[1, 2, 3, 4],
[5, 2, 4, 2],
[1, 2, 0, 1]])
newarr = arr.reshape(2, 2, 3)
print ("Original array:\n", arr)
print("---------------")
print ("Reshaped array:\n", newarr)
Output:
Original array:
[[1 2 3 4]
[5 2 4 2]
[1 2 0 1]]
---------------
Reshaped array:
[[[1 2 3]
[4 5 2]]
[[4 2 1]
[2 0 1]]]
7. Flatten Array
Flatten array: We can use flatten method to get a copy of the array collapsed into one dimension.
It accepts order argument. The default value is ????â (for row-major order). Use ????â for column-major order.
Python
# Flatten array
arr = np.array([[1, 2, 3], [4, 5, 6]])
flat_arr = arr.flatten()
print ("Original array:\n", arr)
print ("Fattened array:\n", flat_arr)
Output:
Original array:
[[1 2 3]
[4 5 6]]
Fattened array:
[1 2 3 4 5 6]
Note: The type of array can be explicitly defined while creating the array.
NumPy Array Indexing
Knowing the basics of NumPy array indexing is important for analyzing and manipulating the array object. NumPy in Python offers many ways to do array indexing.
- Slicing: Just like lists in Python, NumPy arrays can be sliced. As arrays can be multidimensional, you need to specify a slice for each dimension of the array.
- Integer array indexing: In this method, lists are passed for indexing for each dimension. One-to-one mapping of corresponding elements is done to construct a new arbitrary array.
- Boolean array indexing: This method is used when we want to pick elements from the array which satisfy some condition.
Python
# Python program to demonstrate
# indexing in numpy
import numpy as np
# An exemplar array
arr = np.array([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]])
# Slicing array
temp = arr[:2, ::2]
print ("Array with first 2 rows and alternate"
"columns(0 and 2):\n", temp)
# Integer array indexing example
temp = arr[[0, 1, 2, 3], [3, 2, 1, 0]]
print ("\nElements at indices (0, 3), (1, 2), (2, 1),"
"(3, 0):\n", temp)
# boolean array indexing example
cond = arr > 0 # cond is a boolean array
temp = arr[cond]
print ("\nElements greater than 0:\n", temp)
Output:
Array with first 2 rows and alternatecolumns(0 and 2):
[[-1. 0.]
[ 4. 6.]]
Elements at indices (0, 3), (1, 2), (2, 1),(3, 0):
[ 4. 6. 0. 3.]
Elements greater than 0:
[ 2. 4. 4. 6. 2.6 7. 8. 3. 4. 2. ]
NumPy Basic Operations
The Plethora of built-in arithmetic functions is provided in Python NumPy.
1. Operations on a single NumPy array
We can use overloaded arithmetic operators to do element-wise operations on the array to create a new array. In the case of +=, -=, *= operators, the existing array is modified.
Python
# Python program to demonstrate
# basic operations on single array
import numpy as np
a = np.array([1, 2, 5, 3])
# add 1 to every element
print ("Adding 1 to every element:", a+1)
# subtract 3 from each element
print ("Subtracting 3 from each element:", a-3)
# multiply each element by 10
print ("Multiplying each element by 10:", a*10)
# square each element
print ("Squaring each element:", a**2)
# modify existing array
a *= 2
print ("Doubled each element of original array:", a)
# transpose of array
a = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]])
print ("\nOriginal array:\n", a)
print ("Transpose of array:\n", a.T)
Output:
Adding 1 to every element: [2 3 6 4]
Subtracting 3 from each element: [-2 -1 2 0]
Multiplying each element by 10: [10 20 50 30]
Squaring each element: [ 1 4 25 9]
Doubled each element of original array: [ 2 4 10 6]
Original array:
[[1 2 3]
[3 4 5]
[9 6 0]]
Transpose of array:
[[1 3 9]
[2 4 6]
[3 5 0]]
NumPy – Unary Operators
Many unary operations are provided as a method of ndarray class. This includes sum, min, max, etc. These functions can also be applied row-wise or column-wise by setting an axis parameter.
Python
# Python program to demonstrate
# unary operators in numpy
import numpy as np
arr = np.array([[1, 5, 6],
[4, 7, 2],
[3, 1, 9]])
# maximum element of array
print ("Largest element is:", arr.max())
print ("Row-wise maximum elements:",
arr.max(axis = 1))
# minimum element of array
print ("Column-wise minimum elements:",
arr.min(axis = 0))
# sum of array elements
print ("Sum of all array elements:",
arr.sum())
# cumulative sum along each row
print ("Cumulative sum along each row:\n",
arr.cumsum(axis = 1))
Output:
Largest element is: 9
Row-wise maximum elements: [6 7 9]
Column-wise minimum elements: [1 1 2]
Sum of all array elements: 38
Cumulative sum along each row:
[[ 1 6 12]
[ 4 11 13]
[ 3 4 13]]
NumPy – Binary Operators
These operations apply to the array elementwise and a new array is created. You can use all basic arithmetic operators like +, -, /, etc. In the case of +=, -=, = operators, the existing array is modified.
Python
# Python program to demonstrate
# binary operators in Numpy
import numpy as np
a = np.array([[1, 2],
[3, 4]])
b = np.array([[4, 3],
[2, 1]])
# add arrays
print ("Array sum:\n", a + b)
# multiply arrays (elementwise multiplication)
print ("Array multiplication:\n", a*b)
# matrix multiplication
print ("Matrix multiplication:\n", a.dot(b))
Output:
Array sum:
[[5 5]
[5 5]]
Array multiplication:
[[4 6]
[6 4]]
Matrix multiplication:
[[ 8 5]
[20 13]]
Also Read: Numpy Binary Operations
NumPy ufuncs
NumPy provides familiar mathematical functions such as sin, cos, exp, etc. These functions also operate elementwise on an array, producing an array as output.
Note: All the operations we did above using overloaded operators can be done using ufuncs like np.add, np.subtract, np.multiply, np.divide, np.sum, etc.
Python
# Python program to demonstrate
# universal functions in numpy
import numpy as np
# create an array of sine values
a = np.array([0, np.pi/2, np.pi])
print ("Sine values of array elements:", np.sin(a))
# exponential values
a = np.array([0, 1, 2, 3])
print ("Exponent of array elements:", np.exp(a))
# square root of array values
print ("Square root of array elements:", np.sqrt(a))
Output:
Sine values of array elements: [ 0.00000000e+00 1.00000000e+00 1.22464680e-16]
Exponent of array elements: [ 1. 2.71828183 7.3890561 20.08553692]
Square root of array elements: [ 0. 1. 1.41421356 1.73205081]
Also Read: Numpy ufunc
NumPy Sorting Arrays
There is a simple np.sort() method for sorting Python NumPy arrays. Let’s explore it a bit.
Python
# Python program to demonstrate sorting in numpy
import numpy as np
a = np.array([[1, 4, 2],
[3, 4, 6],
[0, -1, 5]])
# sorted array
print ("Array elements in sorted order:\n",
np.sort(a, axis = None))
# sort array row-wise
print ("Row-wise sorted array:\n",
np.sort(a, axis = 1))
# specify sort algorithm
print ("Column wise sort by applying merge-sort:\n",
np.sort(a, axis = 0, kind = 'mergesort'))
# Example to show sorting of structured array
# set alias names for dtypes
dtypes = [('name', 'S10'), ('grad_year', int), ('cgpa', float)]
# Values to be put in array
values = [('Hrithik', 2009, 8.5), ('Ajay', 2008, 8.7),
('Pankaj', 2008, 7.9), ('Aakash', 2009, 9.0)]
# Creating array
arr = np.array(values, dtype = dtypes)
print ("\nArray sorted by names:\n",
np.sort(arr, order = 'name'))
print ("Array sorted by graduation year and then cgpa:\n",
np.sort(arr, order = ['grad_year', 'cgpa']))
Output:
Array elements in sorted order:
[-1 0 1 2 3 4 4 5 6]
Row-wise sorted array:
[[ 1 2 4]
[ 3 4 6]
[-1 0 5]]
Column wise sort by applying merge-sort:
[[ 0 -1 2]
[ 1 4 5]
[ 3 4 6]]
Array sorted by names:
[('Aakash', 2009, 9.0) ('Ajay', 2008, 8.7) ('Hrithik', 2009, 8.5)
('Pankaj', 2008, 7.9)]
Array sorted by graduation year and then cgpa:
[('Pankaj', 2008, 7.9) ('Ajay', 2008, 8.7) ('Hrithik', 2009, 8.5)
('Aakash', 2009, 9.0)]
We have covered the NumPy library of Python in this article, and covered all major concepts you need to know. NumPy is very popular and widely used Python Library.
Hope you will learn and implement NumPy in your projects.
Read More:
NumPy Introduction – FAQs
What is the Basic Function of NumPy?
The basic function of NumPy is to provide an efficient array structure (called ndarray) for storing and manipulating dense data buffers in a contiguous block of memory. This structure allows for efficient operations on large numerical datasets, often with operations executed in compiled code for performance. NumPy arrays support vectorized operations, broadcasting, and various mathematical functions that are essential for scientific computing.
What is the First Entry in NumPy?
In NumPy, the first entry in an array can be accessed by indexing, similar to how lists are indexed in Python. For a one-dimensional array, you access the first entry with an index of 0:
import numpy as np
arr = np.array([10, 20, 30, 40])
first_entry = arr[0]
print(first_entry) # Output: 10
For multi-dimensional arrays, you can access elements using a tuple of indices:
matrix = np.array([[1, 2], [3, 4]])
first_entry = matrix[0, 0]
print(first_entry) # Output: 1
What are NumPy Commands?
NumPy commands refer to the functions and methods available in the NumPy library that operate on arrays. Here are a few commonly used NumPy commands:
np.array(): Create an array.np.arange(): Return evenly spaced values within a given interval.np.zeros(), np.ones(), np.full(): Create new arrays filled with zeros, ones, or a specified value, respectively.np.dot(): Dot product of two arrays.np.reshape(): Gives a new shape to an array without changing its data.np.mean(), np.median(), np.std(): Compute the mean, median, and standard deviation of array elements.np.linalg.inv(): Compute the (multiplicative) inverse of a matrix.
These commands and many others make NumPy a versatile tool for numerical computing in Python
Similar Reads
NumPy Tutorial - Python Library
NumPy is a powerful library for numerical computing in Python. It provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays. NumPyâs array objects are more memory-efficient and perform better than Python lists, whi
7 min read
Introduction
NumPy Introduction
NumPy is an open-source Python library that provides support for large, multi-dimensional arrays and matrices. It also have a collection of high-level mathematical functions to operate on arrays. Features of NumPyNumPy has various features which make them popular over lists. Provides powerful, multi
13 min read
Python Numpy
Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python. Besides its obvious scientific uses, Numpy can also be used as an efficient
7 min read
NumPy Array in Python
Python lists are a substitute for arrays, but they fail to deliver the performance required while computing large sets of numerical data. To address this issue we use the NumPy library of Python. NumPy offers an array object called ndarray. They are similar to standard Python sequences but differ in
6 min read
Basics of NumPy Arrays
NumPy stands for Numerical Python. It is a Python library used for working with an array. In Python, we use the list for the array but it's slow to process. NumPy array is a powerful N-dimensional array object and is used in linear algebra, Fourier transform, and random number capabilities. It provi
5 min read
Numpy | ndarray
N-Dimensional array(ndarray) in NumpyArray 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 i
9 min read
Data type Object (dtype) in NumPy Python
Every ndarray has an associated data type (dtype) object. This data type object (dtype) informs us about the layout of the array. This means it gives us information about: Type of the data (integer, float, Python object, etc.)Size of the data (number of bytes)The byte order of the data (little-endia
3 min read
Creating NumPy Array
Numpy | Array Creation
In this article, we are going to explore numpy array creation technique. Table of Content Array creation using List : Array creation using array functionsMethods for array creation in NumpyArray creation using List : Arrays are used to store multiple values in one single variable.Python does not hav
7 min read
numpy.arange() in Python
The arange([start,] stop[, step,][, dtype]) : Returns an array with evenly spaced elements as per the interval. The interval mentioned is half-opened i.e. [Start, Stop) Parameters : start : [optional] start of interval range. By default start = 0 stop : end of interval range step : [optional] step s
2 min read
numpy.zeros() in Python
The numpy.zeros() function returns a new array of given shape and type, with zeros. Syntax: numpy.zeros(shape, dtype = None, order = 'C') Parameter: shape: integer or sequence of integers â Defines the shape of the new array. Can be a single integer or a tuple.dtype: optional, default is float â The
3 min read
NumPy | Create array filled with all ones
To create an array filled with all ones, given the shape and type of array we can use numpy.ones() method of NumPy library in Python. Example: C/C++ Code import numpy as np array = np.ones(5) print(array) Output: [1. 1. 1. 1. 1.]SyntaxSyntax: np.ones(shape, dtype=None, order='C', *, like=None) Param
2 min read
NumPy linspace() Method | Create Evenly Spaced Array
The NumPy.linspace() function returns an array of evenly spaced values within the specified interval [start, stop]. It is similar to NumPy.arange() function but instead of a step, it uses a sample number. SyntaxSynatx: numpy.linspace(start, stop, num=50, endpoint=True , retstep=False, dtype=None, a
3 min read
numpy.eye() in Python
numpy.eye(R, C = None, k = 0, dtype = type <'float'>) : -The eye tool returns a 2-D array with 1's as the diagonal and 0's elsewhere. The diagonal can be main, upper, or lower depending on the optional parameter k. A positive k is for the upper diagonal, a negative k is for the lower, and a 0
2 min read
Creating a one-dimensional NumPy array
The One-dimensional array contains elements only in one dimension. In other words, the shape of the NumPy array should contain only one value in the tuple. Let us see how to create 1-dimensional NumPy arrays. Create 1-D NumPy Array using Array() FunctionIn NumPy, you can create a 1-D array using the
3 min read
How to create an empty and a full NumPy array?
Creating arrays is a basic operation in NumPy. Empty array: This is an array that isnât initialized with any specific values. Itâs like a blank page, ready to be filled with data later. However, it will contain random leftover values in memory until you update it.Full array: This is an array where a
3 min read
Create a Numpy array filled with all zeros | Python
In this article, we will learn how to create a Numpy array filled with all zeros, given the shape and type of array. We can use Numpy.zeros() method to do this task. This method takes three parameters, discussed below - shape : integer or sequence of integers order : C_contiguous or F_contiguous C-c
2 min read
How to generate 2-D Gaussian array using NumPy?
In this article, let us discuss how to generate a 2-D Gaussian array using NumPy. To create a 2 D Gaussian array using the Numpy python module. Functions used:numpy.meshgrid()- It is used to create a rectangular grid out of two given one-dimensional arrays representing the Cartesian indexing or Matr
2 min read
How to create a vector in Python using NumPy
NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python. Numpy is basically used for creating array of n dimensions. Vector are built
5 min read
Python | Numpy fromrecords() method
With the help of numpy.core.fromrecords() method, we can create the record array by using the list of individual records by using numpy.core.fromrecords() method. Syntax : numpy.core.fromrecords([(tup1), (tup2)], metadata) Return : Return the record of an array. Example #1 : In this example we can s
1 min read
NumPy Array Manipulation
NumPy Copy and View of Array
While working with NumPy, you might have seen some functions return the copy whereas some functions return the view. The main difference between copy and view is that the copy is the new array whereas the view is the view of the original array. In other words, it can be said that the copy is physica
4 min read
How to Copy NumPy array into another array?
Many times there is a need to copy one array to another. Numpy provides the facility to copy array using different methods. In this Copy NumPy Array into Another ArrayThere are various ways to copies created in NumPy arrays in Python, here we are discussing some generally used methods for copies cre
3 min read
Appending values at the end of an NumPy array
Let us see how to append values at the end of a NumPy array. Adding values at the end of the array is a necessary task especially when the data is not fixed and is prone to change. For this task, we can use numpy.append() and numpy.concatenate(). This function can help us to append a single value as
4 min read
How to swap columns of a given NumPy array?
In this article, let's discuss how to swap columns of a given NumPy array. Approach : Import NumPy moduleCreate a NumPy arraySwap the column with IndexPrint the Final array Example 1: Swapping the column of an array. C/C++ Code # importing Module import numpy as np # creating array with shape(4,3) m
2 min read
Insert a new axis within a NumPy array
This post deals with the ways to increase the dimension of an array in NumPy. NumPy provides us with two different built-in functions to increase the dimension of an array i.e., 1D array will become 2D array2D array will become 3D array3D array will become 4D array4D array will become 5D arrayAdd a
4 min read
numpy.hstack() in Python
numpy.hstack() function is used to stack the sequence of input arrays horizontally (i.e. column wise) to make a single array. Syntax : numpy.hstack(tup) Parameters : tup : [sequence of ndarrays] Tuple containing arrays to be stacked. The arrays must have the same shape along all but the second axis.
2 min read
numpy.vstack() in python
numpy.vstack() function is used to stack the sequence of input arrays vertically to make a single array. Syntax : numpy.vstack(tup) Parameters : tup : [sequence of ndarrays] Tuple containing arrays to be stacked. The arrays must have the same shape along all but the first axis. Return : [stacked nda
2 min read
Joining NumPy Array
NumPy provides various functions to combine arrays. In this article, we will discuss some of the major ones. numpy.concatenatenumpy.stacknumpy.block Method 1: Using numpy.concatenate() The concatenate function in NumPy joins two or more arrays along a specified axis. Syntax: numpy.concatenate((array
2 min read
Combining a one and a two-dimensional NumPy Array
Sometimes we need to combine 1-D and 2-D arrays and display their elements. Numpy has a function named as numpy.nditer(), which provides this facility. Syntax: numpy.nditer(op, flags=None, op_flags=None, op_dtypes=None, order='K', casting='safe', op_axes=None, itershape=None, buffersize=0) Example 1
2 min read
Python | Numpy np.ma.concatenate() method
With the help of np.ma.concatenate() method, we can concatenate two arrays with the help of np.ma.concatenate() method. Syntax : np.ma.concatenate([list1, list2]) Return : Return the array after concatenation. Example #1 : In this example we can see that by using np.ma.concatenate() method, we are a
1 min read
Python | Numpy dstack() method
With the help of numpy.dstack() method, we can get the combined array index by index and store like a stack by using numpy.dstack() method. Syntax : numpy.dstack((array1, array2)) Return : Return combined array index by index. Example #1 : In this example we can see that by using numpy.dstack() meth
1 min read
Splitting Arrays in NumPy
NumPy arrays are an essential tool for scientific computing. However, at times, it becomes necessary to manipulate and analyze specific parts of the data. This is where array splitting comes into play, allowing you to break down an array into smaller sub-arrays, making the data more manageable. It i
6 min read
How to compare two NumPy arrays?
Here we will be focusing on the comparison done using NumPy on arrays. Comparing two NumPy arrays determines whether they are equivalent by checking if every element at each corresponding index is the same. Method 1: We generally use the == operator to compare two NumPy arrays to generate a new arra
2 min read
Find the union of two NumPy arrays
To find union of two 1-dimensional arrays we can use function numpy.union1d() of Python Numpy library. It returns unique, sorted array with values that are in either of the two input arrays. Syntax: numpy.union1d(array1, array2) Note The arrays given in input are flattened if they are not 1-dimensio
2 min read
Find unique rows in a NumPy array
In this article, we will discuss how to find unique rows in a NumPy array. To find unique rows in a NumPy array we are using numpy.unique() function of NumPy library. Syntax of np.unique() in Python Syntax: numpy.unique() Parameter: ar: arrayreturn_index: Bool, if True return the indices of the inpu
3 min read
Python | Numpy np.unique() method
With the help of np.unique() method, we can get the unique values from an array given as parameter in np.unique() method. Syntax : np.unique(Array) Return : Return the unique of an array. Example #1 : In this example we can see that by using np.unique() method, we are able to get the unique values f
1 min read
numpy.trim_zeros() in Python
numpy.trim_zeros function is used to trim the leading and/or trailing zeros from a 1-D array or sequence. Syntax: numpy.trim_zeros(arr, trim) Parameters: arr : 1-D array or sequence trim : trim is an optional parameter with default value to be 'fb'(front and back) we can either select 'f'(front) and
2 min read
Matrix in NumPy
Matrix manipulation in Python
In python matrix can be implemented as 2D list or 2D Array. Forming matrix from latter, gives the additional functionalities for performing various operations in matrix. These operations and array are defines in module "numpy". Operation on Matrix : 1. add() :- This function is used to perform eleme
4 min read
numpy matrix operations | empty() function
numpy.matlib.empty() is another function for doing matrix operations in numpy.It returns a new matrix of given shape and type, without initializing entries. Syntax : numpy.matlib.empty(shape, dtype=None, order='C') Parameters : shape : [int or tuple of int] Shape of the desired output empty matrix.
1 min read
numpy matrix operations | zeros() function
numpy.matlib.zeros() is another function for doing matrix operations in numpy. It returns a matrix of given shape and type, filled with zeros. Syntax : numpy.matlib.zeros(shape, dtype=None, order='C') Parameters : shape : [int, int] Number of rows and columns in the output matrix.If shape has length
2 min read
numpy matrix operations | ones() function
numpy.matlib.ones() is another function for doing matrix operations in numpy. It returns a matrix of given shape and type, filled with ones. Syntax : numpy.matlib.ones(shape, dtype=None, order='C') Parameters : shape : [int, int] Number of rows and columns in the output matrix.If shape has length on
2 min read
numpy matrix operations | eye() function
numpy.matlib.eye() is another function for doing matrix operations in numpy. It returns a matrix with ones on the diagonal and zeros elsewhere. Syntax : numpy.matlib.eye(n, M=None, k=0, dtype='float', order='C') Parameters : n : [int] Number of rows in the output matrix. M : [int, optional] Number o
2 min read
numpy matrix operations | identity() function
numpy.matlib.identity() is another function for doing matrix operations in numpy. It returns a square identity matrix of given input size. Syntax : numpy.matlib.identity(n, dtype=None) Parameters : n : [int] Number of rows and columns in the output matrix. dtype : [optional] Desired output data-type
1 min read
Adding and Subtracting Matrices in Python
In this article, we will discuss how to add and subtract elements of the matrix in Python. Example: Suppose we have two matrices A and B. A = [[1,2],[3,4]] B = [[4,5],[6,7]] then we get A+B = [[5,7],[9,11]] A-B = [[-3,-3],[-3,-3]] Now let us try to implement this using Python 1. Adding elements of t
4 min read
Matrix Multiplication in NumPy
Let us see how to compute matrix multiplication with NumPy. We will be using the numpy.dot() method to find the product of 2 matrices. For example, for two matrices A and B. A = [[1, 2], [2, 3]] B = [[4, 5], [6, 7]] So, A.B = [[1*4 + 2*6, 2*4 + 3*6], [1*5 + 2*7, 2*5 + 3*7] So the computed answer wil
2 min read
Numpy ndarray.dot() function | Python
numpy.ndarray.dot() function return the dot product of two arrays. Syntax : numpy.ndarray.dot(arr, out=None) Parameters : arr : [array_like] Input array. out : [ndarray, optional] Output argument. Return : [ndarray] The dot product of two arrays. Code #1 : # Python program explaining # numpy.ndarray
1 min read
NumPy | Vector Multiplication
Vector multiplication is of three types: Scalar Product Dot Product Cross Product Scalar Multiplication: Scalar multiplication can be represented by multiplying a scalar quantity by all the elements in the vector matrix. Code: Python code explaining Scalar Multiplication # importing libraries import
1 min read
How to calculate dot product of two vectors in Python?
In mathematics, the dot product or also known as the scalar product is an algebraic operation that takes two equal-length sequences of numbers and returns a single number. Let us given two vectors A and B, and we have to find the dot product of two vectors. Given that, [Tex]A = a_1i + a_2j + a_3k [/
3 min read
Multiplication of two Matrices in Single line using Numpy in Python
Matrix multiplication is an operation that takes two matrices as input and produces single matrix by multiplying rows of the first matrix to the column of the second matrix.In matrix multiplication make sure that the number of columns of the first matrix should be equal to the number of rows of the
3 min read
Python | Numpy np.eigvals() method
With the help of np.eigvals() method, we can get the eigen values of a matrix by using np.eigvals() method. Syntax : np.eigvals(matrix) Return : Return the eigen values of a matrix. Example #1 : In this example we can see that by using np.eigvals() method, we are able to get the eigen values of a ma
1 min read
How to Calculate the determinant of a matrix using NumPy?
A special number that can be calculated from a square matrix is known as the Determinant of a square matrix. The Numpy provides us the feature to calculate the determinant of a square matrix using numpy.linalg.det() function. Syntax: numpy.linalg.det(array) Example 1: Calculating Determinant of a 2X
2 min read
Python | Numpy matrix.transpose()
With the help of Numpy matrix.transpose() method, we can find the transpose of the matrix by using the matrix.transpose()method in Python. Numpy matrix.transpose() Syntax Syntax : matrix.transpose() Parameter: No parameters; transposes the matrix it is called on. Return : Return transposed matrix Wh
3 min read
Python | Numpy matrix.var()
With the help of Numpy matrix.var() method, we can find the variance of a matrix by using the matrix.var() method. Syntax : matrix.var() Return : Return variance of a matrix Example #1 : In this example we can see that by using matrix.var() method we are able to find the variance of a given matrix.
1 min read
Compute the inverse of a matrix using NumPy
The inverse of a matrix is just a reciprocal of the matrix as we do in normal arithmetic for a single number which is used to solve the equations to find the value of unknown variables. The inverse of a matrix is that matrix which when multiplied with the original matrix will give as an identity mat
2 min read
Operations on NumPy Array
Reshaping NumPy Array
Reshape NumPy Array
NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python. Numpy is basically used for creating array of n dimensions.Reshaping numpy a
5 min read
Python | Numpy matrix.resize()
With the help of Numpy matrix.resize() method, we are able to resize the shape of the given matrix. Remember all elements should be covered after resizing the given matrix. Syntax : matrix.resize(shape) Return: new resized matrix Example #1 : In the given example we are able to resize the given matr
1 min read
Python | Numpy matrix.reshape()
With the help of Numpy matrix.reshape() method, we are able to reshape the shape of the given matrix. Remember all elements should be covered after reshaping the given matrix. Syntax : matrix.reshape(shape) Return: new reshaped matrix Example #1 : In the given example we are able to reshape the give
1 min read
NumPy Array Shape
The shape of an array can be defined as the number of elements in each dimension. Dimension is the number of indices or subscripts, that we require in order to specify an individual element of an array. How can we get the Shape of an Array?In NumPy, we will use an attribute called shape which return
2 min read
Change the dimension of a NumPy array
Let's discuss how to change the dimensions of an array. In NumPy, this can be achieved in many ways. Let's discuss each of them. Method #1: Using Shape() Syntax : array_name.shape() C/C++ Code # importing numpy import numpy as np def main(): # initialising array print('Initialised array') gfg = np.a
3 min read
numpy.ndarray.resize() function - Python
numpy.ndarray.resize() function change shape and size of array in-place. Syntax : numpy.ndarray.resize(new_shape, refcheck = True) Parameters : new_shape :[tuple of ints, or n ints] Shape of resized array. refcheck :[bool, optional] If False, reference count will not be checked. Default is True. Ret
1 min read
Flatten a Matrix in Python using NumPy
Let's discuss how to flatten a Matrix using NumPy in Python. By using ndarray.flatten() function we can flatten a matrix to one dimension in python. Syntax:numpy_array.flatten(order='C') order:'C' means to flatten in row-major.'F' means to flatten in column-major.'A' means to flatten in column-major
1 min read
numpy.moveaxis() function | Python
numpy.moveaxis() function move axes of an array to new positions. Other axes remain in their original order. Syntax : numpy.moveaxis(arr, source, destination) Parameters : arr : [ndarray] input array. source : [ int or sequence of int] Original positions of the axes to move. These must be unique. de
1 min read
numpy.swapaxes() function | Python
numpy.swapaxes() function interchange two axes of an array. Syntax : numpy.swapaxes(arr, axis1, axis2) Parameters : arr : [array_like] input array. axis1 : [int] First axis. axis2 : [int] Second axis. Return : [ndarray] In earlier NumPy versions, a view of arr is returned only if the order of the ax
1 min read
Python | Numpy matrix.swapaxes()
With the help of matrix.swapaxes() method, we are able to swap the axes a matrix by using the same method. Syntax : matrix.swapaxes() Return : Return matrix having interchanged axes Example #1 : In this example we are able to swap the axes of a matrix by using matrix.swapaxes() method. # import the
1 min read
numpy.vsplit() function | Python
numpy.vsplit() function split an array into multiple sub-arrays vertically (row-wise). vsplit is equivalent to split with axis=0 (default), the array is always split along the first axis regardless of the array dimension. Syntax : numpy.vsplit(arr, indices_or_sections) Parameters : arr : [ndarray] A
2 min read
numpy.hsplit() function | Python
numpy.hsplit() function split an array into multiple sub-arrays horizontally (column-wise). hsplit is equivalent to split with axis=1, the array is always split along the second axis regardless of the array dimension. Syntax : numpy.hsplit(arr, indices_or_sections) Parameters : arr : [ndarray] Array
2 min read
Numpy MaskedArray.reshape() function | Python
numpy.MaskedArray.reshape() function is used to give a new shape to the masked array without changing its data.It returns a masked array containing the same data, but with a new shape. The result is a view on the original array; if this is not possible, a ValueError is raised. Syntax : numpy.ma.resh
3 min read
Python | Numpy matrix.squeeze()
With the help of matrix.squeeze() method, we are able to squeeze the size of a matrix by using the same method. But remember one thing we use this method on Nx1 size of matrix which gives out as 1xN matrix. Syntax : matrix.squeeze() Return : Return a squeezed matrix Example #1 : In this example we a
1 min read
Indexing NumPy Array
Basic Slicing and Advanced Indexing in NumPy
Indexing a NumPy array means accessing the elements of the NumPy array at the given index. There are two types of indexing in NumPy: basic indexing and advanced indexing. Slicing a NumPy array means accessing the subset of the array. It means extracting a range of elements from the data. In this tut
5 min read
numpy.compress() in Python
The numpy.compress() function returns selected slices of an array along mentioned axis, that satisfies an axis. Syntax: numpy.compress(condition, array, axis = None, out = None) Parameters : condition : [array_like]Condition on the basis of which user extract elements. Applying condition on input_ar
2 min read
Accessing Data Along Multiple Dimensions Arrays in Python Numpy
NumPy (Numerical Python) is a Python library that comprises of multidimensional arrays and numerous functions to perform various mathematical and logical operations on them. NumPy also consists of various functions to perform linear algebra operations and generate random numbers. NumPy is often used
3 min read
How to access different rows of a multidimensional NumPy array?
Let us see how to access different rows of a multidimensional array in NumPy. Sometimes we need to access different rows of multidimensional NumPy array-like first row, the last two rows, and even the middle two rows, etc. In NumPy , it is very easy to access any rows of a multidimensional array. Al
3 min read
numpy.tril_indices() function | Python
numpy.tril_indices() function return the indices for the lower-triangle of an (n, m) array. Syntax : numpy.tril_indices(n, k = 0, m = None) Parameters : n : [int] The row dimension of the arrays for which the returned indices will be valid. k : [int, optional] Diagonal offset. m : [int, optional] Th
1 min read
Arithmetic operations on NumPyArray
NumPy Array Broadcasting
Broadcasting simplifies mathematical operations on arrays with different shapes. It enables NumPy to efficiently apply operations element-wise without explicitly copying or reshaping data. It automatically adjusts the smaller array to match the shape of the larger array by replicating its values alo
6 min read
Estimation of Variable | set 1
Variability: It is the import dimension that measures the data variation i.e. whether the data is spread out or tightly clustered. Also known as Dispersion When working on data sets in Machine Learning or Data Science, involves many steps - variance measurement, reduction, and distinguishing random
3 min read
Python: Operations on Numpy Arrays
NumPy is a Python package which means 'Numerical Python'. It is the library for logical computing, which contains a powerful n-dimensional array object, gives tools to integrate C, C++ and so on. It is likewise helpful in linear based math, arbitrary number capacity and so on. NumPy exhibits can lik
3 min read
How to use the NumPy sum function?
NumPy's sum() function is extremely useful for summing all elements of a given array in Python. In this article, we'll be going over how to utilize this function and how to quickly use this to advance your code's functionality. Let's go over how to use these functions and the benefits of using this
4 min read
numpy.divide() in Python
numpy.divide(arr1, arr2, out = None, where = True, casting = 'same_kind', order = 'K', dtype = None) : Array element from first array is divided by elements from second element (all happens element-wise). Both arr1 and arr2 must have same shape and element in arr2 must not be zero; otherwise it will
3 min read
numpy.inner() in python
numpy.inner(arr1, arr2): Computes the inner product of two arrays. Parameters : arr1, arr2 : array to be evaluated. Return: Inner product of the two arrays. Code #1 : # Python Program illustrating # numpy.inner() method import numpy as geek # Scalars product = geek.inner(5, 4) print("inner Prod
1 min read
Absolute Deviation and Absolute Mean Deviation using NumPy | Python
Absolute value: Absolute value or the modulus of a real number x is the non-negative value of x without regard to its sign. For example absolute value of 7 is 7 and the absolute value of -7 is also 7. Deviation: Deviation is a measure of the difference between the observed value of a variable and so
3 min read
Calculate standard deviation of a Matrix in Python
In this article we will learn how to calculate standard deviation of a Matrix using Python. Standard deviation is used to measure the spread of values within the dataset. It indicates variations or dispersion of values in the dataset and also helps to determine the confidence in a modelâs statistica
2 min read
numpy.gcd() in Python
numpy.gcd(arr1, arr2, out = None, where = True, casting = âsame_kindâ, order = âKâ, dtype = None) : This mathematical function helps user to calculate GCD value of |arr1| and |arr2| elements. Greatest Common Divisor (GCD) of two or more numbers, which are not all zero, is the largest positive number
1 min read
Linear Algebra in NumPy Array
Numpy | Linear Algebra
The Linear Algebra module of NumPy offers various methods to apply linear algebra on any numpy array.One can find: rank, determinant, trace, etc. of an array.eigen values of matricesmatrix and vector products (dot, inner, outer,etc. product), matrix exponentiationsolve linear or tensor equations and
6 min read
Get the QR factorization of a given NumPy array
In this article, we will discuss QR decomposition or QR factorization of a matrix. QR factorization of a matrix is the decomposition of a matrix say 'A' into 'A=QR' where Q is orthogonal and R is an upper-triangular matrix. We factorize the matrix using numpy.linalg.qr() function. Syntax : numpy.lin
2 min read
How to get the magnitude of a vector in NumPy?
The fundamental feature of linear algebra are vectors, these are the objects having both direction and magnitude. In Python, NumPy arrays can be used to depict a vector. There are mainly two ways of getting the magnitude of vector: By defining an explicit function which computes the magnitude of a g
3 min read
How to compute the eigenvalues and right eigenvectors of a given square array using NumPY?
In this article, we will discuss how to compute the eigenvalues and right eigenvectors of a given square array using NumPy library. Example: Suppose we have a matrix as: [[1,2], [2,3]] Eigenvalue we get from this matrix or square array is: [-0.23606798 4.23606798] Eigenvectors of this matrix are: [[
2 min read
NumPy and Random Data
Random sampling in numpy | ranf() function
numpy.random.ranf() is one of the function for doing random sampling in numpy. It returns an array of specified shape and fills it with random floats in the half-open interval [0.0, 1.0). Syntax : numpy.random.ranf(size=None) Parameters : size : [int or tuple of ints, optional] Output shape. If the
2 min read
Random sampling in numpy | random() function
numpy.random.random() is one of the function for doing random sampling in numpy. It returns an array of specified shape and fills it with random floats in the half-open interval [0.0, 1.0). Syntax : numpy.random.random(size=None) Parameters : size : [int or tuple of ints, optional] Output shape. If
2 min read
Random sampling in numpy | random_sample() function
numpy.random.random_sample() is one of the function for doing random sampling in numpy. It returns an array of specified shape and fills it with random floats in the half-open interval [0.0, 1.0). Syntax : numpy.random.random_sample(size=None) Parameters : size : [int or tuple of ints, optional] Out
2 min read
Random sampling in numpy | sample() function
In Python numpy.random.sample() is one of the functionsgenerate that generates floating-point values in an open interval [0.0,1.0). It doesn't take up any arguments and produces a single random value each time it's called. This function is often used for statistical and simulation tasks in Python. S
2 min read
Random sampling in numpy | random_integers() function
numpy.random.random_integers() is one of the function for doing random sampling in numpy. It returns an array of specified shape and fills it with random integers from low (inclusive) to high (exclusive), i.e. in the interval [low, high). Syntax : numpy.random.random_integers(low, high=None, size=No
2 min read
Random sampling in numpy | randint() function
numpy.random.randint() is one of the function for doing random sampling in numpy. It returns an array of specified shape and fills it with random integers from low (inclusive) to high (exclusive), i.e. in the interval [low, high). Syntax : numpy.random.randint(low, high=None, size=None, dtype='l') P
2 min read
numpy.random.choice() in Python
With the help of choice() method, we can get the random samples of one dimensional array and return the random samples of numpy array. Syntax : numpy.random.choice(a, size=None, replace=True, p=None) Parameters: 1) a - 1-D array of numpy having random samples. 2) size - Output shape of random sample
1 min read
How to choose elements from the list with different probability using NumPy?
We will see How to use numpy.random.choice() method to choose elements from the list with different probability. Syntax: numpy.random.choice(a, size=None, replace=True, p=None) Output: Return the numpy array of random samples. Note: parameter p is probabilities associated with each entry in a(1d-arr
2 min read
How to get weighted random choice in Python?
Weighted random choices mean selecting random elements from a list or an array by the probability of that element. We can assign a probability to each element and according to that element(s) will be selected. By this, we can select one or more than one element from the list, And it can be achieved
3 min read
numpy.random.shuffle() in python
With the help of numpy.random.shuffle() method, we can get the random positioning of different integer values in the numpy array or we can say that all the values in an array will be shuffled randomly. Syntax : numpy.random.shuffle(x) Return : Return the reshuffled numpy array. Example #1 : In this
1 min read
numpy.random.geometric() in Python
With the help of numpy.random.geometric() method, we can get the random samples of geometric distribution and return the random samples of numpy array by using this method. Syntax : numpy.random.geometric(p, size=None) Return : Return the random samples of numpy array. Example #1 : In this example w
1 min read
numpy.random.permutation() in Python
With the help of numpy.random.permutation() method, we can get the random samples of sequence of permutation and return sequence by using this method. Syntax : numpy.random.permutation(x) Return : Return the random sequence of permuted values. Example #1 : In this example we can see that by using nu
1 min read
Sorting and Searching in NumPy Array
Searching in a NumPy array
Numpy provides various methods for searching different kinds of numerical values, in this article, we will cover two important ones. numpy.where()numpy.searchsorted() 1. numpy.where:() It returns the indices of elements in an input array where the given condition is satisfied. Syntax: numpy.where(co
3 min read
NumPy Array Sorting | How to sort NumPy Array
Sorting an array is a very important step in data analysis as it helps in ordering data, and makes it easier to search and clean. In this tutorial, we will learn how to sort an array in NumPy. You can sort an array in NumPy: Using np.sort() functionin-line sortsorting along different axesUsing np.ar
4 min read
Numpy | Sorting, Searching and Counting
SortingSorting refers to arranging data in a particular format. Sorting algorithm specifies the way to arrange data in a particular order. Most common orders are in numerical or lexicographical order. In Numpy, we can perform various sorting operations using the various functions that are provided i
6 min read
Variations in different Sorting techniques in Python
These are all different types for sorting techniques that behave very differently. Let's study which technique works how and which one to use. Let 'a' be a numpy array a.sort() (i) Sorts the array in-place & returns None (ii) Return type is None (iii) Occupies less space. No copy created as it d
3 min read
numpy.sort_complex() in Python
numpy.sort_complex() function is used to sort a complex array.It sorts the array by using the real part first, then the imaginary part. Syntax : numpy.sort_complex(arr) Parameters : arr : [array_like] Input array. Return : [complex ndarray] A sorted complex array. Code #1 : # Python program explaini
1 min read
Python | Numpy np.ma.mini() method
With the help of np.ma.mini() method, we can get the minimum value of masked array by using np.ma.mini() method. Syntax : np.ma.mini() Return : Return the minimum value of masked array. Example #1 : In this example we can see that by using np.ma.mini() method, we are able to get the minimum value of
1 min read
Python | Numpy matrix.sort()
With the help of matrix.sort() method, we are able to sort the values in a matrix by using the same method. Syntax : matrix.sort() Return : Return a sorted matrix Example #1 : In this example we are able to sort the elements in the matrix by using matrix.sort() method. # import the important module
1 min read
Python | Numpy matrix.argsort()
With the help of Numpy matrix.argmax() method, we are able to find the sort the elements in the given matrix having one or more dimension and it would return the index value of sorted elements. Syntax : matrix.argsort() Return : Return index number of sorted elements in matrix Example #1 : In this e
1 min read
Projects and Applications with NumPy