seb
seb

Reputation: 2321

appending integers to empty NumPy array in Python

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.

Upvotes: 1

Views: 1761

Answers (1)

NPE
NPE

Reputation: 500883

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]))

Upvotes: 1

Related Questions