【问题标题】:Iterating in numpy arrays在numpy数组中迭代
【发布时间】:2016-11-23 10:57:40
【问题描述】:

我在遍历我的 numpy 数组时遇到问题。我有两个函数(f 和 g)和 x 轴的时间戳。首先,我确定了 f 和 g 的截距。然后我想计算拦截发生了多少次,而我的函数 f 的 大于 0。 运行代码后出现以下错误。 (我也试过 f.all() ):

具有多个元素的数组的真值是不明确的。 使用 a.any() 或 a.all()

代码如下:

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

感谢您的帮助!

【问题讨论】:

  • 最后一次迭代没有意义。也不要使用nditer。直接迭代。

标签: python arrays loops numpy for-loop


【解决方案1】:

ValueErrorif f > 0: 行抛出。你有f 作为一个数字数组,你问它在哪里是正数:f > 0 给你一个布尔值数组。 if 语句需要一个布尔表达式,但您不能将布尔数组强制转换为单个布尔值。

正如异常消息所述,要使用您拥有的代码,您需要将f > 0 更改为(f > 0).any()(f > 0).all()

您的问题听起来好像您正在尝试做的是计算indexTrue 的次数,其中f 在同一位置是正数(也就是说,您的实际意思是if f[i+1] > 0:)。如果是这种情况,你可以试试:

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

我将在此处指出逐一索引(f[i+1]f[1:]),这是为了纠正 numpy.diff 使 indexf 小一项。

【讨论】:

    猜你喜欢
    • 2018-09-26
    • 2013-01-04
    • 2021-06-02
    • 2018-04-13
    • 2013-05-05
    • 2011-10-03
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多