1

I have a NumPy array that stores the information of a signal. In the code below I have just created it from random numbers for convenience. Now I need to select positions from the signal array, based on criteria. Again, I have simplified the criteria below, for sake of brevity. I am trying to store those positions by appending them to an empty NumPy array called positions. I know that my use of the NumPy.append() function must be wrong. I tried to debug it, but I cannot find the bug. What am I doing wrong?

import numpy as np
import numpy.random as random

signal = random.randint(1,10000,1000)

positions = np.array([],dtype = int)
for i in range(0,len(signal)):
    if((signal[i] % 3 == 0) or (signal[i] % 5 == 0)):
        print(i)
        np.append(positions,i)

print(positions)

EDIT:

I actually need this to run in a for loop, since my condition in the if() is a mathematical expression that will be changed according to some rule (that would be way to complicated to post here) if the condition is met.

1 Answer 1

1

You don't need an explicit loop for this:

positions = np.where((signal % 3 == 0) | (signal % 5 == 0))[0]

Here, (signal % 3 == 0) | (signal % 5 == 0) evaluates the criterion on every element of signal, and np.where() returns the indices where the criterion is true.

If you have to append to positions in a loop, here is one way to do it:

positions = np.hstack((positions, [i]))
Sign up to request clarification or add additional context in comments.

3 Comments

@sebastian: When used in this way, np.where() returns a single-element tuple. The [0] unwraps the single element.
I implemented the change. Problem is, my true code is much more complex than the one above. I actually need to run this in a for loop, since the condition in the if() changes (I edited the question).
@sebastian: positions = np.hstack((positions, [i]))

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.