【问题标题】:Numpy iteration and append [duplicate]Numpy迭代和追加[重复]
【发布时间】:2020-01-22 10:31:44
【问题描述】:

我基本上是在尝试遍历数组,从第二个元素中减去第一个元素,从第三个元素中减去第二个元素,依此类推,然后将我的结果附加到一个新的 numpy 数组中。

t = np.array([0, 10, 15, 35, 40, 24, 50, 90])

for i in np.nditer(t):
    dt = (t[int(i)] - t[int(i+1)]
    print(dt)
    np.append(dt)

【问题讨论】:

  • 请填写您想要的结果。
  • 替代?还是减法?
  • 不要使用np.append 喜欢列表追加。尽管有名字,但它不一样。

标签: arrays python-3.x loops numpy iteration


【解决方案1】:

如果您想像在原始代码中那样使用迭代和 np.append,您可以这样做:

t = np.array([0, 10, 15, 35, 40, 24, 50, 90])
dt=np.array([]) #defining an array to store the results in
prev=None #defining a variable to store the value of i in the last iteration in

for i in np.nditer(t): #iterating trough the values of t
    if not prev==None: #checking if this is the first iteration
        a=i-prev
        dt=np.append(arr=dt,values=a) #appending a to dt
    prev=i #set prev to the current i to use it in the next iteration
print(dt) #print the result

这不是最优雅的解决方案,但它可以帮助你看到你的错误。

【讨论】:

    【解决方案2】:

    您也可以使用 zip(...) 来获得所需的输出:

    out = np.array(list(v - k for k, v in zip(t, t[1:])))
    # Also you can use:
    # np.fromiter((v - k for k, v in zip(t, t[1:])), int) 
    # and out value is:
    # array([ 10,   5,  20,   5, -16,  26,  40])
    

    【讨论】:

    • 对不起,我不太明白这个
    • @IfeanyiAnene zip是python内置函数,见here
    • @ChihebNexus 我认为 OP 可能在谈论使用就地 for 循环?我建议对您的答案进行修改,这可能会有所帮助。
    • @Enthus3d 它被称为列表理解。见here
    • @ChihebNexus 啊,是的,这个名字让我忘记了。但是,我认为您应该向 OP 而不是我解释这个概念是如何工作的。
    【解决方案3】:

    您可能正在寻找np.diff(..) [numpy-doc],每次都会从前一项中减去一项。

    例如:

    >>> np.diff(np.array([0, 10, 15, 35, 40, 24, 50, 90]))
    array([ 10,   5,  20,   5, -16,  26,  40])
    

    【讨论】:

      猜你喜欢
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      • 2020-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      • 1970-01-01
      相关资源
      最近更新 更多