加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – Numpy沿轴应用并获取行索引

发布时间:2020-12-20 13:16:24 所属栏目:Python 来源:网络整理
导读:我有一个2D数组(它实际上非常大,另一个数组的视图): x = np.array([[0,1,2],[1,2,3],[2,3,4],[3,4,5]] ) 我有一个处理数组的每一行的函数: def some_func(a): """ Some function that does something funky with a row of numbers """ return [a[2],a[0]]
我有一个2D数组(它实际上非常大,另一个数组的视图):

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

我有一个处理数组的每一行的函数:

def some_func(a):
    """
    Some function that does something funky with a row of numbers
    """
    return [a[2],a[0]]  # This is not so funky

np.apply_along_axis(some_func,x)

我正在寻找的是调用np.apply_along_axis函数的一些方法,以便我可以访问行索引(对于正在处理的行),然后能够使用此函数处理每一行:

def some_func(a,idx):
    """
    I plan to use the index for some logic on which columns to
    return. This is only an example
    """
    return [idx,a[2],a[0]]  # This is not so funky

解决方法

对于轴= 1的2d数组,apply_along_axis与数组行的迭代相同

In [149]: np.apply_along_axis(some_func,x)
Out[149]: 
array([[2,0],1],[4,[5,3]])
In [151]: np.array([some_func(i) for i in x])
Out[151]: 
array([[2,3]])

对于axis = 0,我们可以迭代x.T.当数组为3d时,apply_along_axis更有用,我们想要迭代除一个之外的所有维度.然后它节省了一些单调乏味.但它不是速度解决方案.

使用修改后的函数,我们可以使用标准枚举来获取行和索引:

In [153]: np.array([some_func(v,i) for i,v in enumerate(x)])
Out[153]: 
array([[0,5,3]])

或者使用简单的范围迭代:

In [157]: np.array([some_func(x[i],i) for i in range(x.shape[0])])
Out[157]: 
array([[0,3]])

有各种工具可以获得更高维度的索引,例如ndenumerate和ndindex.

快速解决方案 – 一次处理所有行:

In [158]: np.column_stack((np.arange(4),x[:,0]))
Out[158]: 
array([[0,3]])

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读