I want to rebuild the following logic with numpy broadcasting function such as np.where
: From a 2d array check per row if the first element satisfies a condition. If the condition is true then return the first three elements as a row, else the last three elements.
A short MWE in form of a for-loop which I want to circumvent:
JavaScript
x
12
12
1
import numpy as np
2
array = np.array([
3
[1, 2, 3, 4],
4
[1, 2, 4, 2],
5
[2, 3, 4, 6]
6
])
7
8
new_array = np.zeros((array.shape[0], array.shape[1]-1))
9
for i, row in enumerate(array):
10
if row[0] == 1: new_array[i] = row[:3]
11
else: new_array[i] = row[-3:]
12
Advertisement
Answer
If you want to use np.where
:
JavaScript
1
10
10
1
import numpy as np
2
array = np.array([
3
[1, 2, 3, 4],
4
[1, 2, 4, 2],
5
[2, 3, 4, 6]
6
])
7
8
cond = array[:, 0] == 1
9
np.where(cond[:, None], array[:,:3], array[:,-3:])
10
output:
JavaScript
1
4
1
array([[1, 2, 3],
2
[1, 2, 4],
3
[3, 4, 6]])
4
EDIT
slightly more concise version:
JavaScript
1
2
1
np.where(array[:, [0]] == 1, array[:,:3], array[:,-3:])
2