Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index error, delete row from array if column has a value

I have a array 'x' with four columns.

For each row if the 4th column has a value of 1 then I want to delete that entire row:

x = np.array([[1,2,3,0],[11,2,3,24],[1,22,3,1],[1,22,3,1], [5,6,7,8], [9,10,11,1]])
for i in range(0,len(x)):
    if x[i][4]==0:
        x=np.delete(x, i,0)

I get the following error:

Traceback (most recent call last):
File "", line 2, in
if x[i][4]==0:
IndexError: index out of bounds

like image 382
West1234 Avatar asked Nov 30 '25 14:11

West1234


2 Answers

You're trying to reference the fourth column with [4], but since it's zero based it's actually [3]

like image 136
Tom Swifty Avatar answered Dec 03 '25 06:12

Tom Swifty


You can use indexing:

>>> x[x[:,3] != 1]
array([[ 1,  2,  3,  0],
       [11,  2,  3, 24],
       [ 5,  6,  7,  8]])
like image 28
arshajii Avatar answered Dec 03 '25 05:12

arshajii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!