【问题标题】:Apply function n items at a time along axis沿轴一次应用函数 n 项
【发布时间】:2017-04-30 00:31:53
【问题描述】:

我正在寻找一种方法来沿轴同时应用 n 项函数。例如

array([[ 1,  2], 
       [ 3,  4],
       [ 5,  6],
       [ 7,  8]])

如果我一次将 sum 应用于行 2 项,我会得到:

array([[  4,   6], 
       [ 12,  14]])

第 1 2 行和最后 2 行的 sum 是哪个。

注意:我正在处理更大的数组,我必须将函数应用于我可以在运行时决定的 n 个项目。


数据沿不同的轴延伸。例如

array([[... [ 1,  2, ...], 
            [ 3,  4, ...],
            [ 5,  6, ...],
            [ 7,  8, ...],
            ...], ...])

【问题讨论】:

  • 在多个维度上更大。
  • 也许你可以添加一个这样的例子。
  • 添加了一个例子。

标签: python numpy multidimensional-array


【解决方案1】:

将第一个轴拆分为两个轴,使第二个拆分轴的长度为n 以具有一个 3D 数组,然后沿该拆分轴求和,就像这样 -

a.reshape(a.shape[0]//n,n,a.shape[1]).sum(1)

它应该非常有效,因为重塑只是在输入数组中创建一个视图。

示例运行 -

In [55]: a
Out[55]: 
array([[2, 8, 0, 0],
       [1, 5, 3, 3],
       [6, 1, 4, 7],
       [0, 4, 0, 7],
       [8, 0, 8, 1],
       [8, 3, 3, 8]])

In [56]: n = 2 # Sum every two rows

In [57]: a.reshape(a.shape[0]//n,n,a.shape[1]).sum(1)
Out[57]: 
array([[ 3, 13,  3,  3],
       [ 6,  5,  4, 14],
       [16,  3, 11,  9]])

【讨论】:

    【解决方案2】:

    这是一个缩减:

    numpy.add.reduceat(a, [0,2])
    >>> array([[ 4,  6],
               [12, 14]], dtype=int32)
    

    只要“更大”是指在“y”轴上更长,您就可以扩展:

    a = numpy.array([[ 1,  2],
                     [ 3,  4],
                     [ 5,  6],
                     [ 7,  8],
                     [ 9, 10],
                     [11, 12]])
    numpy.add.reduceat(a, [0,2,4])
    >>> array([[ 4,  6],
               [12, 14],
               [20, 22]], dtype=int32)
    

    编辑:实际上,这也适用于“在两个维度上都更大”:

    a = numpy.arange(24).reshape(6,4)
    numpy.add.reduceat(a, [0,2,4])
    >>> array([[ 4,  6,  8, 10],
               [20, 22, 24, 26],
               [36, 38, 40, 42]], dtype=int32)
    

    我会让你自己根据你的具体情况调整索引。

    【讨论】:

    • 有一件事我无法弄清楚[0,2,4] 是什么。最后一个4是什么意思?
    • 在第一个轴(y)方向上,它表示添加范围的“开始”。例如:0:2、2:4、4:end。在最后一个示例中:a[4:,:] 给出array([[16, 17, 18, 19], [20, 21, 22, 23]])
    【解决方案3】:

    这样的事情怎么样?

    n = 2
    # calculate the cumsum along axis 0 and take one row from every n rows
    cumarr = arr.cumsum(axis = 0)[(n-1)::n]                
    
    # calculate the difference of the resulting numpy array along axis 0   
    np.vstack((cumarr[0][None, :], np.diff(cumarr, axis=0)))
    
    # array([[ 4,  6],
    #        [12, 14]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-20
      • 2021-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      • 1970-01-01
      相关资源
      最近更新 更多