Delete a row from a NumPy matrix in Python
In this article, we will discuss how to delete a row from a NumPy matrix in Python with the help of an example. Here, we will use a method named numpy.delete()
to remove a row from a NumPy 2-dimensional array or matrix. So read the tutorial carefully to learn and explore programming.
The Syntax used to delete a row is given below:
Syntax: np.delete(name_of_array,obj,axis=0,None)
Here, is an example to clear all your doubts:
Example: Delete a row from a NumPy matrix
Simply, create a two-dimensional array (4 rows, 5 columns) with NumPy, delete the specified row with help of the method np.delete()
which is mentioned above in the tutorial, and then create the second array with NumPy. For reference, I have mentioned the code below:
# import the numpy module import numpy as np # create an array using integers # creating 4 rows and 5 columns a = np.array([[1, 2, 3, 4, 5], [5, 6, 7, 8, 8], [9, 10, 11, 12,13], [14, 15, 16, 17, 18]]) print(a) # deleting the 0th row data = np.delete(a, 0, 0) print("data after 0 th row deleted :", data) # deleting 1st row data = np.delete(a, 1, 0) print("data after deleting the 1st row :", data) # deleting 2st row data = np.delete(a, 2, 0) print("data after deleting the 2nd row :", data) # deleting 4nd row data = np.delete(a, 3, 0) print("data after deleting the 3rd row :", data)
Output:
As we can see for deleting a row from a NumPy matrix in Python, the first step is to import the NumPy module and then create an array of rows and columns using np.array()
function.
You can make any number of rows and columns according to your environment(Here, I have made 4 rows and 5 columns), then print the matrix. Now use np.delete()
method to delete the specified row of NumPy matrix in Python. Under the np.delete()
method of Python (name of array, obj, axis) of matrix is mentioned to delete a row of the NumPy matrix. As you can see in the example, axis=0 specifies that we want to delete the rows along the vertical axis (i.e., delete one row). Then at last print data after deletion of the specified row in the matrix and a new NumPy matrix will be obtained.
I hope this article helped you to solve your problem.
Leave a Reply