gis_grad_student
gis_grad_student

Reputation: 184

Deleting slices from numpy array given a condition

I have a numpy array t_i of shape (6, 2000, 2). I need to delete column slices from the array if all the elements in that slice below that row is -1. Let's say I am in ith row of t_i. Now for those columns below the ith row where every element in the column is [-1,-1] I need to delete the complete column slice from t_i.

I tried this:

t_iF = t_i[:, t_i[i+1:] != -1]

But I am getting this error:

IndexError: too many indices for array: array is 3-dimensional, but 4 were indexed

Can you all please point me to the right direction? Thanks!

Updated: Let t_i be:

t1=np.arange(32).reshape(4,4,2)
t1[1:,[1,3]] = -1

In this case the whole 1 and 3 column slices need to be deleted.

Upvotes: 0

Views: 294

Answers (1)

Stefan B
Stefan B

Reputation: 1677

np.any can be very helpful for tasks like these:

import numpy as np

t1 = np.arange(32).reshape(4, 4, 2)
t1[1:, [1, 3]] = -1

t_filtered = t1[:, [np.any(t1[i, i:] != -1) for i in range(t1.shape[0])], :]
print(t_filtered.shape) # (4, 3, 2)

Upvotes: 1

Related Questions