Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mask a 2D numpy array based on values in one column

Suppose I have the following numpy array:

a = [[1, 5, 6],
     [2, 4, 1],
     [3, 1, 5]]

I want to mask all the rows which have 1 in the first column. That is, I want

   [[--, --, --],
     [2, 4, 1],
     [3, 1, 5]]

Is this possible to do using numpy masked array operations? How can one do it?

Thanks.

like image 579
Curious2learn Avatar asked Jan 07 '11 13:01

Curious2learn


People also ask

How do you mask a 2D array in Python?

To mask rows and/or columns of a 2D array that contain masked values, use the np. ma. mask_rowcols() method in Numpy. The function returns a modified version of the input array, masked depending on the value of the axis parameter.

How do you split a 2D array in NumPy Python?

For splitting the 2d array,you can use two specific functions which helps in splitting the NumPy arrays row wise and column wise which are split and hsplit respectively . 1. split function is used for Row wise splitting. 2.

What does [: :] mean on NumPy arrays?

The [:, :] stands for everything from the beginning to the end just like for lists. The difference is that the first : stands for first and the second : for the second dimension. a = numpy. zeros((3, 3)) In [132]: a Out[132]: array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])

How do I filter an element from a NumPy array?

In NumPy, you filter an array using a boolean index list. A boolean index list is a list of booleans corresponding to indexes in the array. If the value at an index is True that element is contained in the filtered array, if the value at that index is False that element is excluded from the filtered array.


1 Answers

import numpy as np

a = np.array([[1, 5, 6],
              [2, 4, 1],
              [3, 1, 5]])

np.ma.MaskedArray(a, mask=(np.ones_like(a)*(a[:,0]==1)).T)

# Returns: 
masked_array(data =
 [[-- -- --]
 [2 4 1]
 [3 1 5]],
             mask =
 [[ True  True  True]
 [False False False]
 [False False False]])
like image 150
eumiro Avatar answered Oct 23 '22 10:10

eumiro