【问题标题】:Numpy apply along axis based on row indexNumpy 基于行索引沿轴应用
【发布时间】:2021-07-29 08:59:31
【问题描述】:

尝试基于row index position应用numpy内置函数apply_along_axis

import numpy as np
sa = np.array(np.arange(4))
sa_changed = (np.repeat(sa.reshape(1,len(sa)),repeats=2,axis=0))
print (sa_changed)

操作:

[[0 1 2 3]
 [0 1 2 3]]

功能:

np.apply_along_axis(lambda x: x+10,0,sa_changed)

操作:

array([[10, 11, 12, 13],
       [10, 11, 12, 13]])

但是有没有办法基于row index position使用这个函数,例如,如果它是even row index,那么add 10,如果它是odd row index,那么add 50

示例:

def func(x):
   if x.index//2==0:
      x = x+10
   else:
      x = x+50
   return x

【问题讨论】:

  • apply_along_axis 不是速度工具。它可以使代码看起来更漂亮,尤其是当数组是 3d 或更大时,但它不会更快。
  • 顺便说一句,// 是整数除法,而不是模数
  • @hpaulj 感谢您的解决方案。对于更快的方法,您还有其他建议吗?不是确切的代码,只是建议就可以了。

标签: python python-3.x numpy numpy-ndarray numpy-ufunc


【解决方案1】:

这是一种方法

import numpy as np

x = np.array([[0, 1, 2, 3],
     [0, 1, 2, 3]])

y = x.copy() # if you dont wish to modify x

对于偶数行索引

y[::2] = y[::2] + 10 

对于奇数行索引

y[1::2] = y[1::2] + 50

输出:

array([[10, 11, 12, 13],
       [50, 51, 52, 53]])

【讨论】:

    【解决方案2】:

    直接或使用apply_along_axis 迭代数组时,子数组没有.index 属性。所以我们必须将一个明确的索引值传递给你的函数:

    In [248]: def func(i,x):
         ...:    if i//2==0:
         ...:       x = x+10
         ...:    else:
         ...:       x = x+50
         ...:    return x
         ...: 
    In [249]: arr = np.arange(10).reshape(5,2)
    

    apply 无法添加此索引,因此我们必须使用显式迭代。

    In [250]: np.array([func(i,v) for i,v in enumerate(arr)])
    Out[250]: 
    array([[10, 11],
           [12, 13],
           [54, 55],
           [56, 57],
           [58, 59]])
    

    将 // 替换为 %

    In [251]: def func(i,x):
         ...:    if i%2==0:
         ...:       x = x+10
         ...:    else:
         ...:       x = x+50
         ...:    return x
         ...: 
    In [252]: np.array([func(i,v) for i,v in enumerate(arr)])
    Out[252]: 
    array([[10, 11],
           [52, 53],
           [14, 15],
           [56, 57],
           [18, 19]])
    

    但更好的方法是完全跳过迭代:

    制作一个添加行的数组:

    In [253]: np.where(np.arange(5)%2,10,50)
    Out[253]: array([50, 10, 50, 10, 50])
    

    通过broadcasting申请:

    In [256]: x+np.where(np.arange(5)%2,50,10)[:,None]
    Out[256]: 
    array([[10, 11],
           [52, 53],
           [14, 15],
           [56, 57],
           [18, 19]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 2018-07-08
      • 2022-10-30
      • 2015-09-17
      • 2012-01-29
      • 1970-01-01
      相关资源
      最近更新 更多