1

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

0

1 Answer 1

1

: 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]]])
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the quick response! This works nicely in the interactive mode, but somehow within my script I get a new error: toChange = [0, 0, slice(None, None, None)] TypeError: 'numpy.ndarray' object is not callable Is there a possibility that toChange is considered to be an array?
Using a tuple to do ND-indexes is preferable. List/Sequence usage depends on shaky logic and I would personally prefer to just forbid it.
Ok, I got the problem: the slicing didn't work, because before manipulating the array I was writing the whole array to a file using with open("out/histData.txt", "w") as dataFile: for slice in histData: np.savetxt(dataFile, slice, fmt="%.2f", delimiter="\t") Therefore slice was an ndarray and the whole thing didn't work. Amateur hour :-) @seberg: how would this solution look like?
@Gnihilo, exactly the same, just make sure toChange is a tuple at the end (if you need the mutability if the list, just call tuple(toChange))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.