开发者

Removing Array Elements in Python while keeping track of their position

I'v got two numpy arrays. The first array contains some zeros (which ar开发者_运维技巧e 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!


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])


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])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜