BadBytes
BadBytes

Reputation: 31

How to converse an array of n-column labels to 1-column?

this is a label array that I use in my classification model:

array([[1, 0, 0],
   [0, 1, 0],
   [0, 0, 1]], dtype=uint8)

But I'd like to reverse it to one column, so it will look like this:

  array([[0],
   [1],
   [2]], dtype=uint8)

Any suggestions are appreciated.

Upvotes: 1

Views: 102

Answers (3)

ansev
ansev

Reputation: 30930

You could use np.argmax

np.argmax(arr, axis=1).reshape(arr.shape[0], 1).astype(np.int8)

# array([[0],
#        [1],
#        [2]], dtype=int8)

If you want to take always the position of the ones:

np.argmax(arr==1, axis=1)

Upvotes: 3

nipun
nipun

Reputation: 692

arr = np.array([[1,0,0], [0,1,0], [0,0,1]])

def pos(lis):
    return np.where(lis == 1)[0]

posvec = np.apply_along_axis(pos, 1, arr)

Upvotes: 1

robbo
robbo

Reputation: 545

If you only have one valid value in your original array per row (as in your example) and, assuming you called that array a you could use numpy's where() function, like np.where(a) and get the second array that is returned. E.g. np.where(a)[1].

This only works if the values that you want to omit are 0 or False.

That second array contains the positions where the values in the columns evaluate to True.

Upvotes: 1

Related Questions