2

I have a numpy array, A of size nx1 where each value is a number between 0 and 9.

I would like to create a new array, B of size nx10 such that in B[i] we store a numpy array that contains zeros and a 1 in position A[i].

For example:

A array
[[9]
 [2]
 [4]
 [1]
 [8]]

B array
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
 [0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
 [0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
 [0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
 [0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]

Is there an elegant way of doing this with numpy?

ksm001
  • 3,772
  • 10
  • 36
  • 57

3 Answers3

3

Create a new empty array using numpy.zeros, its size is going to be (arr.size, arr.max()), now fill the items on those positions using multi-dimensional indexing:

>>> arr = np.array([[9], [2], [4], [1], [8]])
>>> arr_ = np.zeros((arr.size, arr.max()))
>>> arr_[np.arange(arr.size), arr[:,0]-1] = 1
>>> arr_
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.],
       [ 0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.],
       [ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.]])
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

Something like this would do it:

A = [[9],[2],[4],[1],[8]]
B = [[1 if i == j[0] else 0 for i in range(10)] for j in A]

This is a list-based approach; you can simply use np.asarray on B to get the numpy matrix, or create a 10x10 matrix of zeros in numpy and fill 1s in the positions dictated by the A array.

The latter generalises to the case where A's elements might have more than one item.

Jake
  • 822
  • 5
  • 14
0

You could do something like this, assuming an NP Nx1 array of X:

max_val = max(X)
length_arr = len(X)
new_arr = np.zeros((max_val,length_arr))

This will create the array of the right size that you want.

for i in range(len(X)):
    new_arr[i][X[i]-1]=1

Should then assign the correct values in place?

Works fine in my test case.

Henry
  • 1,646
  • 12
  • 28