[Numpy-discussion] How construct custom slice

Keith Goodman kwgoodman@gmail....
Mon Dec 27 12:48:48 CST 2010


On Mon, Dec 27, 2010 at 10:36 AM, Mario Moura <moura.mario@gmail.com> wrote:
> Hi Folks
>
> a = np.zeros((4,3,5,55,5),dtype='|S8')
> myLen = 4 # here I use myLen = len(something)
> li = [3,2,4] # li from a list.append(something)
> sl = slice(0,myLen)
> tmpIndex = tuple(li) + sl + 4  # <== Here my problem
> a[tmpIndex]
>
> # So What I want is:
> fillMe = np.array(['foo','bar','hello','world'])
> # But I cant contruct by hand like this
> a[3,2,4,:4,4] = fillMe
> a
>
> Again. I need construct custom slice from here
> tmpIndex = tuple(li) + sl + 4
> a[tmpIndex]

First let's do it by hand:

>> a = np.zeros((4,3,5,55,5),dtype='|S8')
>> fillMe = np.array(['foo','bar','hello','world'])
>> a[3,2,4,:4,4] = fillMe

Now let's try using an index:

>> b = np.zeros((4,3,5,55,5),dtype='|S8')
>> myLen = 4
>> li = [3,2,4]
>> sl = slice(0,myLen)

Make index:

>> idx = range(a.ndim)
>> idx[:3] = li
>> idx[3] = sl
>> idx[4] = 4
>> idx = tuple(idx)

Compare results:

>> b[idx] = fillMe
>> (a == b).all()
   True


More information about the NumPy-Discussion mailing list