I have an array like this: This is an extension of a recent question that I asked elsewhere here. I have a numpy array like this:
JavaScript
x
12
12
1
data = np.array([
2
[1,2,3],
3
[1,2,3],
4
[1,2,101],
5
[4,5,111],
6
[4,5,6],
7
[4,5,6],
8
[4,5,101],
9
[4,5,112],
10
[4,5,6],
11
])
12
In the third column, I want the value to be replaced with 10001 if the next one along is 101
AND if the current one is 6
. which would result in an array like this:
JavaScript
1
12
12
1
data = np.array([
2
[1,2,3],
3
[1,2,3],
4
[1,2,101],
5
[4,5,111],
6
[4,5,6],
7
[4,5,10001],
8
[4,5,101],
9
[4,5,112],
10
[4,5,6],
11
])
12
Any help on this would be greatly appreciated! Thanks!
Advertisement
Answer
One way using numpy.roll
:
JavaScript
1
3
1
s = data[:, 2]
2
data[np.logical_and(s == 6, np.roll(s, -1) == 101), 2] = 10001
3
Output:
JavaScript
1
10
10
1
array([[ 1, 2, 3],
2
[ 1, 2, 3],
3
[ 1, 2, 101],
4
[ 4, 5, 111],
5
[ 4, 5, 6],
6
[ 4, 5, 10001],
7
[ 4, 5, 101],
8
[ 4, 5, 112],
9
[ 4, 5, 6]])
10