2
m = np.random.randint(4,size=(4,4,4))

Let's say I want to create separate arrays for each integer like this

mm=[]
mm.append((m==1).astype(int))
mm.append((m==2).astype(int))
mm.append((m==3).astype(int))

I was wondering if there is a better way to do this without having to explicitly define m==1, etc. Is it possible to implement an implicit expansion approach in python as easily as it is in Matlab for multidimensional arrays as shown in this post?

1
  • 1
    MATLAB has finally added broadcasting! Commented Aug 1, 2018 at 21:35

2 Answers 2

6

To have a ndim-array as the output, leveraging broadcasting -

mm = m == np.arange(1,4)[:,None,None,None]

Note that we are using None which is an alias for np.newaxis to extend dimensions for the range array so that with the equality comparison we are effectively doing elementwise comparison against all elements in m against all in the range-array. This is needed so that broadcasting is affected.

For a generic case of comparing a n-dim array m against an array of values, say : ar = np.array([1,2,3]), we would use a reshaping to bring on the same dimension-extending effect, like so -

mm = m == ar.reshape((-1,)+(1,)*m.ndim)

Or, use the built-in np.equal.outer, as we are essentially doing outer equality comparison -

mm = np.equal.outer(ar,m)

Finally, convert to int for int dtype array : mm.astype(int).

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

5 Comments

nice broadcasting! +1
@Divakar: Thanks, this works great. However I don't understand why it works... What is the meaning of [:,None,None,None] in this case?
@HappyPy Added few comments for clarification.
@Divakar: Many thanks for the additional edits and explanation.
The key to broadcasting is that dimensions can be added automatically at the start, but have to be explicit at the end. That's what the Nones are doing.
3
mm = [(m==n).astype(int) for n in np.unique(m)]

will give you the masks on m for all unique values in m

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.