Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

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]))
share|improve this answer
    
thanks, what does the [0] in the very end do? –  lomppi Apr 1 '13 at 8:36
    
@sebastian: When used in this way, np.where() returns a single-element tuple. The [0] unwraps the single element. –  NPE Apr 1 '13 at 8:38
    
ahhh... ok, awesome –  lomppi Apr 1 '13 at 8:38
    
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). –  lomppi Apr 1 '13 at 8:43
    
@sebastian: positions = np.hstack((positions, [i])) –  NPE Apr 1 '13 at 8:45
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.