Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Transform a 3D numpy array to 1D based on column value

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

How can I do this?

>Solution :

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.empty(len(preds))
out.fill(np.nan)

out[x] = y

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading