0

I'm trying to do the following, just misunderstand where I'm wrong:

In: import numpy as np

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

In: for i in range(a.shape[1]):
        a[:, i] = np.ma.masked_where(~a[:, i].any(), a[:, i])

Out: array([[0., 1., --],
     [1., 2., --],
     [0., 3., --]])

The point here is to mask only the third column because it's completely zeros, and leave the first column zeros unmasked

8
  • Very unclear what you are trying to accomplish here. Commented Jan 22, 2018 at 21:26
  • --- is not a valid Python identifier. Commented Jan 22, 2018 at 21:28
  • 1
    perhaps updating the question and removing the comments? Commented Jan 22, 2018 at 21:31
  • 1
    @Alex -- is what NumPy will output when a value is masked. Commented Jan 22, 2018 at 22:00
  • You haven't asked an actual question, but I assume your question is: why are there (still) two non-masked zeros in the final output. But please update your question with your actual question. Commented Jan 22, 2018 at 22:02

2 Answers 2

1

You can't invert (~) floating point numbers and arrays.

Try with:

a = np.ma.masked_where(np.isclose(a, 0), a)

(no for loop needed either.)

Sign up to request clarification or add additional context in comments.

Comments

0

One approach to mask based on all zeros in a column is simply to identify column sums of zero. Below is my solution, borrowing very heavily off of this SO answer to provide a simple mechanism for masking after you have gotten the column indices of interest.

import numpy as np    

def mask_zero_cols(in_array):
    # idx is an array of column indices for all-zero columns
    idx = np.where(in_array.sum(axis=0) == 0)[0] #axis=0 is for columns
    m = np.zeros_like(in_array)
    m[:, idx] = 1

    return np.ma.masked_array(in_array, m)


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

a_mask = mask_zero_cols(a)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.