Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional index in 2d array in python

I have a 2D array, g, like so:

np.array([
[1 2 3 4], 
[5 6 7 8], 
[9 10 11 12]
])

So g[0] returns the first row, in other words when I give an index of 0, I get the first row. When I use an index of 1, I get the second row:

g[1] = [5 6 7 8]

and so on.

But I want to return all rows where the index of g is NOT a certain value. Eg. I want to return g[x] for all x where x != 1.

I know how to use conditional indexing with 1D arrays, but what about 2D arrays? I'm confused here because I'm not putting conditions on what indices to retrieve according to the values, but I need a condition dependent on the indices themselves.

like image 576
user961627 Avatar asked Sep 17 '25 11:09

user961627


1 Answers

You could use np.arange(len(g)) != 1 to create a boolean index:

In [137]: g
Out[137]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

In [138]: g[np.arange(len(g)) != 1]
Out[138]: 
array([[ 1,  2,  3,  4],
       [ 9, 10, 11, 12]])

If you really want to eliminate just one row, you could, alternatively, use np.concatenate to join two basic slices:

In [143]: np.concatenate([g[:1], g[2:]])
Out[143]: 
array([[ 1,  2,  3,  4],
       [ 9, 10, 11, 12]])

For large arrays, the first method appears to be faster, however:

In [150]: g2 = np.tile(g, (10000,1))

In [153]: %timeit g2[np.arange(len(g)) != 1]
100000 loops, best of 3: 6.9 µs per loop

In [152]: %timeit np.concatenate([g2[:1], g2[2:]])
10000 loops, best of 3: 51.8 µs per loop
like image 88
unutbu Avatar answered Sep 19 '25 01:09

unutbu