Trying to apply numpy
inbuilt function apply_along_axis
based on row index position
JavaScript
x
5
1
import numpy as np
2
sa = np.array(np.arange(4))
3
sa_changed = (np.repeat(sa.reshape(1,len(sa)),repeats=2,axis=0))
4
print (sa_changed)
5
OP:
JavaScript
1
3
1
[[0 1 2 3]
2
[0 1 2 3]]
3
The function:
JavaScript
1
2
1
np.apply_along_axis(lambda x: x+10,0,sa_changed)
2
Op:
JavaScript
1
3
1
array([[10, 11, 12, 13],
2
[10, 11, 12, 13]])
3
But is there a way to use this function based on row index position
for example, if its a even row index
then add 10
and if its a odd row index
then add 50
Sample:
JavaScript
1
7
1
def func(x):
2
if x.index//2==0:
3
x = x+10
4
else:
5
x = x+50
6
return x
7
Advertisement
Answer
When iterating on array, directly or with apply_along_axis
, the subarray does not have a .index
attribute. So we have to pass an explicit index value to your function:
JavaScript
1
9
1
In [248]: def func(i,x):
2
if i//2==0: :
3
x = x+10 :
4
else: :
5
x = x+50 :
6
return x :
7
:
8
In [249]: arr = np.arange(10).reshape(5,2)
9
apply
doesn’t have a way to add this index, so instead we have to use an explicit iteration.
JavaScript
1
8
1
In [250]: np.array([func(i,v) for i,v in enumerate(arr)])
2
Out[250]:
3
array([[10, 11],
4
[12, 13],
5
[54, 55],
6
[56, 57],
7
[58, 59]])
8
replacing // with %
JavaScript
1
15
15
1
In [251]: def func(i,x):
2
if i%2==0: :
3
x = x+10 :
4
else: :
5
x = x+50 :
6
return x :
7
:
8
In [252]: np.array([func(i,v) for i,v in enumerate(arr)])
9
Out[252]:
10
array([[10, 11],
11
[52, 53],
12
[14, 15],
13
[56, 57],
14
[18, 19]])
15
But a better way is to skip the iteration entirely:
Make an array of the row additions:
JavaScript
1
3
1
In [253]: np.where(np.arange(5)%2,10,50)
2
Out[253]: array([50, 10, 50, 10, 50])
3
apply it via broadcasting
:
JavaScript
1
8
1
In [256]: x+np.where(np.arange(5)%2,50,10)[:,None]
2
Out[256]:
3
array([[10, 11],
4
[52, 53],
5
[14, 15],
6
[56, 57],
7
[18, 19]])
8