3

What is best way of doing: given a 1-D array of discrete variables size N (here N=4) and X is the number of unique elements, I am trying to create a multidimensional array of size (N*X) where elements are 1 or 0 depending on the occurrence of elements in the 1-D array, e.g. Following array_1D (N=4 and X=3) will result in array_ND of size 3*4:

array_1D = np.array([x, y, z, x])
array_ND = [[1 0 0 1]
            [0 1 0 0]
            [0 0 1 0]]

Thanks,

Aso

2
  • Your result will not be NxN--even your example is 3x4. Commented Oct 30, 2013 at 13:43
  • @WarrenWeckesser you are right. I corrected the question after your comment. Commented Oct 30, 2013 at 13:58

2 Answers 2

4

Try this:

(np.unique(a)[..., None] == a).astype(np.int)

You can leave out the .astype(np.int) part if you want a boolean array. Here we have used broadcasting (the [..., None] part) to avoid explicit looping.

Broken down, as suggested in the comments:

>>> import numpy as np
>>> a = np.array([1, 2, 3, 1])
>>> unique_elements = np.unique(a)
>>> result = unique_elements[..., None] == a
>>> unique_elements
array([1, 2, 3])
>>> result
array([[ True, False, False,  True],
       [False,  True, False, False],
       [False, False,  True, False]], dtype=bool)
2
  • 2
    I was just about to give almost the same answer. :) You should probably separate this into two steps. The user will want to save the array returned by np.unique(a), in order to know the meaning of the values in the array. Commented Oct 30, 2013 at 13:49
  • Thanks @MrE for your perfect answer. Numpy is just great! Commented Oct 30, 2013 at 13:52
2

If the initial array contains valid indexes from 0 to n - 1 then you can write

eye = np.eye(3)
array_1D = np.array([0, 1, 2, 0])
array_ND = eye[array_1D]

The resulting matrix will be

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

which is the transpose of the one you expect.

What's happening here is that numpy uses the elements of array_1D as row indices of eye. So the resulting matrix contains as many rows as the elements of array_1D and each one of them relates to the respective element. (0 relates to 1 0 0, etc.)

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.