0

I have a numpy array like this:

data = np.array([
     [1,2,3],
     [1,2,3],
     [1,2,101],
     [4,5,111],   
     [4,5,6], 
     [4,5,6], 
     [4,5,101], 
     [4,5,112], 
     [4,5,6], 
     ])

In the third column, I want the value to be replaced with 10001 if the next one along is 101. which would result in an array like this:

data = np.array([
     [1,2,3],
     [1,2,10001],
     [1,2,101],
     [4,5,111],   
     [4,5,6], 
     [4,5,10001], 
     [4,5,101], 
     [4,5,112], 
     [4,5,6], 
     ])

I tried this which I was certain would work but it doesn't...

dith = np.nditer(data[:, 2], op_flags=['readwrite'])
for i in dith:
    if i+1 == 3:
        i[...] = 10001

If anyone could help with this then that would be great.

2 Answers 2

1

Try this -

data[np.roll(data==101,-1,0)] = 10001
array([[    1,     2,     3],
       [    1,     2, 10001],
       [    1,     2,   101],
       [    4,     5,   111],
       [    4,     5,     6],
       [    4,     5, 10001],
       [    4,     5,   101],
       [    4,     5,   112],
       [    4,     5,     6]])

Only assumption here is that your first row doesn't contain a 101


In case there is a potential scenario that 101 may occur in the first row of the matrix, then try this approach below.

idx = np.vstack([np.roll(data==101,-1,0)[:-1], np.array([False, False, False])])
data[idx] = 10001
array([[    1,     2,     3],
       [    1,     2, 10001],
       [    1,     2,   101],
       [    4,     5,   111],
       [    4,     5,     6],
       [    4,     5, 10001],
       [    4,     5,   101],
       [    4,     5,   112],
       [    4,     5,     6]])
Sign up to request clarification or add additional context in comments.

1 Comment

wow thanks! How would you limit this to act only on the 3rd column? The way it works now, if there was a 101 in the first or second then the preceding value would also be changed.
1
indices_of_101 = np.where(data[:, 2] == 101)[0]
if indices_of_101[0] = 0:  # taking into accound boundary problem
    indices_of_101 = indices_of_101[1:]
data[:, indices_of_101-1] = 10001

1 Comment

this looks great! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.