Tom
Tom

Reputation: 1027

Iterating in numpy arrays

I have a problem with iterating through my numpy array. I have two functions (f and g) and the Timestamp for the x-axis. First, I determined the interception of f and g. Then I wanted to counter how many times the interception happens, while the values of my function f are greater than 0. I got the following error after running the code. (Also I tried f.all() ):

The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Here is the code:

import pandas as pd
import numpy as np


df = pd.read_csv("Sensor2.csv", delimiter=";", parse_dates=True)

df.drop('x', axis=1, inplace=True)
df.drop('y', axis=1, inplace=True)

df["100MA"] = pd.rolling_mean(df["z"], 100, min_periods=1)
df["200MA"] = pd.rolling_mean(df["z"], 200, min_periods=1)


x = np.array(df['Timestamp'])
f = np.array(df['100MA'])
g = np.array(df['200MA'])


index = np.argwhere((np.diff(np.sign(f - g)) != 0)).reshape(-1).astype(int)


counter = 0

for i in np.nditer(index):
    if f > 0:
        counter = counter +1
        print counter

Thank you for your help!

Upvotes: 0

Views: 118

Answers (1)

wildwilhelm
wildwilhelm

Reputation: 5019

The ValueError is being thrown by the line if f > 0:. You have f as an array of numbers, and you're asking where it is positive: f > 0 gives you an array of boolean values. The if statement expects a boolean expression, but you can't coerce the boolean array to a single boolean value.

As the exception message states, to go with the code you have, you need to change f > 0 to (f > 0).any() or (f > 0).all().

Your question makes it sound like what you're trying to do is count the number of times that index is True, where f is positive at the same location (that is, what you actually meant was if f[i+1] > 0:). If this is the case, you can try:

index = np.diff(np.sign(f - g)) != 0
counter = (f[1:][index] > 0).sum()

I'll point out the off-by-one indexing here (f[i+1] and f[1:]), which is to correct for numpy.diff making index one item smaller than f.

Upvotes: 2

Related Questions