1

I've got a simple 2d numpy array like this

array([[1, 0, 1],
       [1, 1, 0],
       [0, 1, 1],
       [0, 0, 0],
       [1, 0, 0]])

What I'm trying to do is multiply each row of the array by itself to form a 3d array, (so that 1*1 = 1 and anything else will be 0, essentailly an and function):

array([[[1,0,1],[1,0,0],[0,0,1],[0,0,0],[1,0,0]],
       [[1,0,0],[1,1,0],[0,1,0],[0,0,0],[1,0,0]],
       ...,
       ...,
       ...])

1 Answer 1

1

Turns out the answer is pretty simple. If the array is x:

x[np.newaxis,:,:]*x[:,np.newaxis,:]

And this works with things such as logical expressions, if you want to just compare on identical elements in each row, you could do something like:

np.logical_not(np.logical_xor(x[np.newaxis,:,:], x[:,np.newaxis,:]))

Which would return:

array([[[ True,  True,  True],
        [ True, False, False],
        [False, False,  True],
        [False,  True, False],
        [ True,  True, False]],

       [[ True, False, False],
        [ True,  True,  True],
        [False,  True, False],
        [False, False,  True],
        [ True, False,  True]],

       ...,
       ...,
       ...], dtype=bool)
Sign up to request clarification or add additional context in comments.

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.