【问题标题】:How to subtract the previous rows column from current column and create a new dimension in the array with this value using numpy?如何从当前列中减去前一行列并使用 numpy 在数组中创建一个具有此值的新维度?
【发布时间】:2012-07-02 15:19:07
【问题描述】:

我想要做的是获取当前数组并从当前行列值中减去前一行列值。我还想获取结果并将其作为新维度添加到数组中。

示例数组:

[[1,2,4,7,9,15], [3, 4,3,5,10,2], [5,6,56,7,20,1]]

假设我想对第 4 列执行此操作,因此我希望输出是一个如下所示的数组:

[[1,2,4,7,9,15,0], [3, 4,3,5,10,2,-2], [5,6,56,7,20,1,2]]

谢谢

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    您可以使用np.diffconcatenate 选项的组合来执行此操作,如下所示:

    import numpy as np
    myarray = np.array([[1,2,4,7,9,15], [3, 4,3,5,10,2], [5,6,56,7,20,1]])
    #your differences appears to be wraparound, so we repeat the last row at the top:
    myarray_wrap = np.vstack((myarray[-1],myarray))
    #this gets the diffs for all columns:
    column_diffs = np.diff(myarray_wrap, axis=0)
    #now we add in only the the column_diff that we want, at the end:
    print np.hstack((myarray, column_diffs[:,3].reshape(-1,1)))
    #Output:
    [[ 1  2  4  7  9 15  0]
     [ 3  4  3  5 10  2 -2]
     [ 5  6 56  7 20  1  2]]
    

    【讨论】:

    • 区别不是环绕实际上我只是在第一行使用 0 作为占位符我怎么能在不环绕的情况下实现这个?
    • @user1440194 - 在顶部重复第一行而不是最后一行。将np.vstack((myarray[-1],myarray)) 更改为np.vstack((myarray[0],myarray))
    【解决方案2】:

    这段 Python 代码应该可以解决您的问题。

    previous = None
    for row in rows:
     current = row[4]
     row.append( 0 if previous == None else current - previous )
     previous = current
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-14
      • 2021-01-23
      • 2022-01-26
      • 2019-11-10
      • 1970-01-01
      • 2019-04-16
      相关资源
      最近更新 更多