Delete Row from NumPy Array that contains a specific value
In this tutorial, we will be learning how to delete a row from Numpy array that contains a specific value in Python. (Numerical Python).
You may be thinking, “This looks so easy”. Yes, You may feel that way but it is a bit tricky while programming and for that, you need to be aware of some NumPy array functions. If you are not aware, relax, because I will cover those for you. So let’s get started.
Remove row from NumPy Array containing a specific value in Python
First of all, we need to import NumPy in order to perform the operations.
import numpy as np
You may or may not write “as Your_name“. It is done so that we do not have to write numpy again and again in our code. Your_name can be anything you like.
Next, Using numpy, we need to create a 2D array, which is nothing but multiple lists and we need to store our array in a variable let’s say arr.
arr=np.array([[1,2,3],[4,5,6],[7,8,9]])
array() is a function used to create array which contains multiple lists separated by comma. If you do not know about creating 2D lists in python, learn here.
Now, lets declare a variable varĀ that contains the value whose row is to be deleted.
var=3
Now, We need to iterate the array arr to find our value inside it. This can be done as follows.
for i in range(0,2): for x in arr[i]: if(x==val):
After we find the value, we need to delete the containing row. For that, we use delete() function that takes 3 arguments.
- Array_name
- Index of containing list.
- axis (If we do not mention axis then our list gets flattened i.e, Converts into 1D array)
if axis=0, it means we are choosing row-wise deletion and if axis=1, then it means column wise deletion.
Let’s see how to do it.
if(x==val): arr=np.delete(arr,i,0)
We modified our existing array arrĀ with the new array which does not has the row containing the value var=3.
Alternatively, you can name your new array something else.
So, now we have an array which does not has the row containing the value 3
finally, we print our array to see the required output.
print(arr)
Let’s see how our code looks like.
import numpy as np arr=np.array([[1,2,3],[4,5,6],[7,8,9]]) val=3 for i in range(0,2): for x in arr[i]: if(x==val): arr=np.delete(arr,i,0) print(arr)
Output:
[[4 5 6] [7 8 9]]
Also, learn
- how to find the position of an element in a list in Python
- Python | Select a random item from a list in Python
Nicely explained, was looking for the same stuff
I’m glad you found it helpful.