Gnihilo
Gnihilo

Reputation: 15

Passing list as slice for a N-dimensional numpy array

I'm trying to manipulate the values of a N-dimensional array based on the user's decision, at which index the array should be changed. This example works fine:

import numpy as np
a = np.arange(24).reshape(2,3,4)

toChange = ['0', '0', '0'] #input from user via raw_input

a[toChange] = 0

But if I want to change not only one position but a complete row, I run into problems:

toChange = ['0', '0', ':'] #input from user via raw_input

a[toChange] = 0

This causes ValueError: setting an array element with a sequence. I can see that the problem is the ':' string, because a[0, 0, :] = 0 does exactly what I want. The question is, how to pass the string to the array?

Or is there a smarter way to manipulate user-defined slices?

PS: as I'm working on an oldstable Debian I use Python 2.6.6 and Numpy 1.4.1

Upvotes: 1

Views: 704

Answers (1)

Fred Foo
Fred Foo

Reputation: 363587

: is syntactic sugar for a slice object:

>>> class Indexable(object):
...     def __getitem__(self, idx):
...         return idx
...     
>>> Indexable()[0, 0, :]
(0, 0, slice(None, None, None))

So if you replace ':' with slice(None, None, None) you get the desired result:

>>> toChange = [0, 0, slice(None, None, None)]
>>> a[toChange] = 0
>>> a
array([[[ 0,  0,  0,  0],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])

Upvotes: 1

Related Questions