Filter a 2D numpy array

家住魔仙堡 提交于 2019-12-12 07:28:28

问题


I want to have a sub array (between min and max) of a numpy 2D ndarray

    xy_dat = get_xydata()
    x_displayed = xy_dat[((xy_dat > min) & (xy_dat < max))]

min and max are float in order to be compare with the first value of the array xy_dat

xy_dat is a 2D numpy array :

[[ 735964.            1020.        ]
 [ 735964.04166667    1020.        ]
 [ 735964.08333333    1020.        ]
 ..., 
 [ 736613.39722222    1095.        ]
 [ 736613.40416667    1100.        ]
 [ 736613.41111111    1105.        ]]

x_displayed is correctly filtered but I have lost the second value (it is now a 1D array) :

[ 735964.04166667  735964.08333333  735964.125      
 ...,  
736613.39027778  736613.39722222  736613.40416667]

How make the filter on the first value and keep the other ?


回答1:


You should perform the condition only over the first column:

x_displayed = xy_dat[((xy_dat[:,0] > min) & (xy_dat[:,0] < max))]

What we do here is constructing a view where we only take into account the first column with xy_dat[:,0]. By now checking if this 1d is between bounds, we construct a 1D boolean array of the rows we should retain, and now we make a selection of these rows by using it as item in the xy_dat[..] parameter.



来源:https://stackoverflow.com/questions/47885848/filter-a-2d-numpy-array

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