【问题标题】:Arithmetic operation along dynamically specified axis沿动态指定轴的算术运算
【发布时间】:2020-05-01 09:13:19
【问题描述】:

我想对动态指定的轴和索引进行算术运算,并更新原始数组中的值,例如:

import numpy as np

array = np.array([[[1, 2],
                   [3, 4],
                   [5, 6]],
                  [[7, 8],
                   [9, 10],
                   [11, 12]]])
axis = 1
indices = [0,2]

例如给指定的轴和索引加1,得到新数组为:

array = [[[2, 3],
          [3, 4],
          [6, 7]],
         [[8, 9],
          [9, 10],
          [12, 13]]])

【问题讨论】:

  • 我不喜欢通过比较两个数组来推断你在做什么。你应该用工作代码来说明清楚——即使它不像你想要的那样快速或动态。

标签: python numpy


【解决方案1】:

如果你想要一个循环使用:

import numpy as np

array = np.array([[[1, 2],
                   [3, 4],
                   [5, 6]],
                  [[7, 8],
                   [9, 10],
                   [11, 12]]])
indices = [0, 2]

for i in array:
    i[[0, 2]] += 1

【讨论】:

    【解决方案2】:
    import numpy as np
    
    array = np.array([[[1, 2],
                       [3, 4],
                       [5, 6]],
                      [[7, 8],
                       [9, 10],
                       [11, 12]]])
    indices = [0, 2]
    
    # either like this
    array[:, indices, :] += 1
    
    # or using a for loop
    for idx in range(len(array)):  
       array[idx, indices, :] += 1
    
    print(array)
    

    【讨论】:

    • 它不能解决我的问题;我想在循环中动态更改轴(尺寸)
    • 我不明白你的意思。
    • 我正在使用一个循环,它的轴值在每次迭代中都会发生变化,从 0 到 len(array)。更多说明:在循环一中,我有 array[indices, : , :] += 1;在循环 2 中,我有 array[:, indices, :] += 1;在循环 3 中,我有 array[:, :, indices] += 1,等等更高维度!
    【解决方案3】:

    我在这篇文章中得到了答案:Slicing a numpy array along a dynamically specified axis 就我而言:

    def slicer(array, indices, axis):
        selection = [slice(None)] * array.ndim
        selection[axis] = indices
        return tuple(selection)
    

    slice(None) 等价于:。最后:

    array[slicer(array, indices, axis)] += 1
    

    【讨论】:

      猜你喜欢
      • 2014-08-15
      • 1970-01-01
      • 2011-06-30
      • 1970-01-01
      • 1970-01-01
      • 2016-03-10
      • 1970-01-01
      • 2017-10-24
      • 2015-04-02
      相关资源
      最近更新 更多