views:

218

answers:

2

Hi!

I'v got two numpy arrays. The first array contains some zeros (which are distributed randomly over the length of the array), which I would like to remove.

My issue is that I would also like to remove the entries of the second array at the index positions where the first array elements are zero.

I only came up with a very cumbersome for-loop. Does anyone have an "elegant" method for doing this?

Thx!

+4  A: 

Is it what you want? I am a NumPy newbie.

In [1]: import numpy as np

In [2]: a = np.array([1,2,0,3,0,4])

In [3]: b = np.array([1,2,3,4,5,6])

In [4]: b[np.where(a)]  
Out[4]: array([1, 2, 4, 6])

In [5]: np.where(a)  
Out[5]: (array([0, 1, 3, 5]),)

In [6]: a[np.where(a)]  
Out[6]: array([1, 2, 3, 4])
sunqiang
This is the way I usually do it, but there is an even simpler method. `np.extract(a,b)`. It does the same as `b[np.where(a)]`.
AFoglia
@AFoglia, thanks for the introduction of np.extract. it's really cool.
sunqiang
That's exactly what I looked for, thanks!
Dzz
@Dzz, Glad it helped :)
sunqiang
A: 

You can use boolean indexing. x!=0 gives you a boolean array with True where x!=0 false where x==0. If you index either x or y with this array (ie x_nozeros=x[x!=0]) then you will get only the elements where x!=0. eg:

In [1]: import numpy as np
In [2]: x = np.array([1,2,0,3,0,4])
In [3]: y = np.arange(1,7)
In [4]: indx = x!=0
In [5]: x_nozeros = x[indx]
In [6]: y_nozeros = y[indx]
In [7]: x_nozeros
Out[7]: array([1, 2, 3, 4])
In [8]: y_nozeros
Out[8]: array([1, 2, 4, 6])
thrope