Maybe this is a very simple task, but I have a numpy.ndarray with shape (1988,3).
JavaScript
x
8
1
preds = [[1 0 0]
2
[0 1 0]
3
[0 0 0]
4
5
[0 1 0]
6
[1 0 0]
7
[0 0 1]]
8
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,
JavaScript
1
2
1
new_preds = [0 1 NaN 1 0 2]
2
How can I do this?
Advertisement
Answer
You can use numpy.nonzero
:
JavaScript
1
9
1
preds = [[1, 0, 0],
2
[0, 1, 0],
3
[0, 0, 1],
4
[0, 1, 0],
5
[1, 0, 0],
6
[0, 0, 1]]
7
8
new_preds = np.nonzero(preds)[1]
9
Output: array([0, 1, 2, 1, 0, 2])
handling rows with no match:
JavaScript
1
13
13
1
preds = [[1, 0, 0],
2
[0, 1, 0],
3
[0, 0, 0],
4
[0, 1, 0],
5
[1, 0, 0],
6
[0, 0, 1]]
7
8
x, y = np.nonzero(preds)
9
10
out = np.full(len(preds), np.nan)
11
12
out[x] = y
13
Output: array([ 0., 1., nan, 1., 0., 2.])