1

Maybe this is a very simple task, but I have a numpy.ndarray with shape (1988,3).

preds = [[1 0 0]
        [0 1 0]
        [0 0 0]
        ...
        [0 1 0]
        [1 0 0]
        [0 0 1]]

I want to create a 1D array with shape=(1988,) that will have values corresponding to the column of my 3D array that has a value of 1.

For example,

 new_preds = [0 1 NaN ... 1 0 2]

How can I do this?

4
  • 1
    try this new_preds = np.argmax(preds, axis=1) Commented Dec 16, 2022 at 13:20
  • Do you only have exactly one 1 per row? If not can you provide an updated example? Commented Dec 16, 2022 at 13:21
  • No, sometimes there might be rows that have only zeros, because the predictions where lower than a certain threshold, so they didn't become 1. Commented Dec 16, 2022 at 13:22
  • Not sure what to do with those predictions actually, maybe the best idea would be to drop them or change them to NaN values, any ideas? Commented Dec 16, 2022 at 13:24

1 Answer 1

2

You can use numpy.nonzero:

preds = [[1, 0, 0],
         [0, 1, 0],
         [0, 0, 1],
         [0, 1, 0],
         [1, 0, 0],
         [0, 0, 1]]

new_preds = np.nonzero(preds)[1]

Output: array([0, 1, 2, 1, 0, 2])

handling rows with no match:

preds = [[1, 0, 0],
         [0, 1, 0],
         [0, 0, 0],
         [0, 1, 0],
         [1, 0, 0],
         [0, 0, 1]]

x, y = np.nonzero(preds)

out = np.full(len(preds), np.nan)

out[x] = y

Output: array([ 0., 1., nan, 1., 0., 2.])

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

1 Comment

perhaps out = np.full(len(preds), np.nan) instead of empty()/fill()?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.