问题
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
回答1:
You can use indexing:
>>> x[x[:,3] != 1]
array([[ 1, 2, 3, 0],
[11, 2, 3, 24],
[ 5, 6, 7, 8]])
回答2:
You're trying to reference the fourth column with [4], but since it's zero based it's actually [3]
回答3:
The index of a list starts from 0. So, since there are 4 elements, the indexes are :0,1,2,3. So, if you have to check the 4th element, use index 3.
if x[i][3]==0:
pass
This will work
来源:https://stackoverflow.com/questions/18858396/index-error-delete-row-from-array-if-column-has-a-value