I have a 3d numpy array like this (as an example)
JavaScript
x
5
1
a = np.array([
2
[[1, -2, 3, 4],[5, 6, 7, 8]],
3
[[9, 10, 11, 12],[13, 14, 15, 16]]
4
])
5
I want to apply the following operations only to elements within the column with index 1 in the inner dimension. The elements are
[-2,6,10,14]
for the example above. The operations would be:
JavaScript
1
25
25
1
# variables used in the operations
2
v1, v2, v3 = 12, 4, 2
3
4
# the following two operations should only be applied to specified column across all the array
5
6
# 1st operation
7
a[a >= v1] = v1
8
9
# output
10
a = np.array([
11
[[1, -2, 3, 4],[5, 6, 7, 8]],
12
[[9, 10, 11, 12],[13, 12, 15, 16]]
13
])
14
15
# 2nd operation
16
f = lambda x: -2 if(x==-2) else (x-v3)/(v2-v3)
17
a = f(a)
18
19
# output
20
21
a = np.array([
22
[[1, -2, 3, 4],[5, 2, 7, 8]],
23
[[9, 4, 11, 12],[13, 5, 15, 16]]
24
])
25
Can someone help me? I have looked into several NumPy methods but can’t seem to adapt to my example.
Advertisement
Answer
You need to change you function to be vectorial (i.e accept an array and input and return an array as output), and slice to only apply it on the desired “column”:
JavaScript
1
4
1
f = lambda x: np.where(x==-2, -2, (x-v3)/(v2-v3))
2
3
a[ ,[1]] = f(a[ ,[1]])
4
output:
JavaScript
1
6
1
array([[[ 1, -2, 3, 4],
2
[ 5, 2, 7, 8]],
3
4
[[ 9, 4, 11, 12],
5
[13, 5, 15, 16]]])
6