Numpy filter 2D array by two masks

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

I have a 2D array and two masks, one for columns, and one for rows. If I try to simply do data[row_mask,col_mask], I get an error saying shape mismatch: indexing arrays could not be broadcast together with shapes .... On the other hand, data[row_mask][:,col_mask] works, but is not as pretty. Why does it expect indexing arrays to be of the same shape?

Here's a specific example:

import numpy as np data = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) row_mask = np.array([True, True, False, True]) col_mask = np.array([True, True, False]) print(data[row_mask][:,col_mask]) # works print(data[row_mask,col_mask]) # error 

回答1:

Use ix_ function :

>>> data[np.ix_(row_mask,col_mask)] array([[ 1,  2],        [ 4,  5],        [10, 11]]) 

Combining multiple Boolean indexing arrays or a Boolean with an integer indexing array can best be understood with the obj.nonzero() analogy. The function ix_ also supports boolean arrays and will work without any surprises.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!