定期索引numpy.ndarrays

我正在尝试定期访问(读/写)numpy.ndarrays。换句话说,如果我的my_array的形状为 10 * 10 ,并且在输入中使用了访问运算符:

my_arrray[10,10]acess_function(my_array,10,10)

我可以访问元素

my_array[0,0]

我想对定期索引数组的返回元素具有读写功能。

任何人都可以在不移动原始阵列副本的情况下怎么做?

zhanghuiqingIT 回答:定期索引numpy.ndarrays

我认为这可以满足您的要求,但是我不确定是否存在更优雅的产品。可以为Nd数组编写通用函数,但这仅适用于2D。正如您所说的,它使用了模块化算法。

import numpy as np

def access(shape,ixr,ixc):
    """ Returns a selection. """
    return np.s_[ixr % shape[0],ixc % shape[1]]

arr = np.arange(100)
arr.shape = 10,10

arr[ access(arr.shape,45,87) ]
# 57

arr[access(arr.shape,87)] = 100

In [18]: arr 
# array([[  0,1,2,3,4,5,6,7,8,9],#        [ 10,11,12,13,14,15,16,17,18,19],#        [ 20,21,22,23,24,25,26,27,28,29],#        [ 30,31,32,33,34,35,36,37,38,39],#        [ 40,41,42,43,44,46,47,48,49],#        [ 50,51,52,53,54,55,56,**100**,58,59],#        [ 60,61,62,63,64,65,66,67,68,69],#        [ 70,71,72,73,74,75,76,77,78,79],#        [ 80,81,82,83,84,85,86,87,88,89],#        [ 90,91,92,93,94,95,96,97,98,99]])

编辑-通用nD版本

def access(shape,*args):
    if len(shape) != len(args):
        error = 'Inconsistent number of dimemsions: {} & number of indices: {} in coords.'
        raise IndexError( error.format(len(shape),len(args)))
    res = []
    for limit,ix in zip(shape,args):
        res.append(ix % limit)
    return tuple(res)

用法/测试

a = np.arange(24)
a.shape = 2,4
a[access(a.shape,7)]
# 15

a[access(a.shape,7) ] = 100
a
# array([[[  0,3],#         [  4,7],#         [  8,9,10,11]],#        [[ 12,100],#         [ 16,#         [ 20,23]]])
本文链接:https://www.f2er.com/3108825.html

大家都在问