0

I have a rather basic question about the NumPy module in Python 2, particularly the version on trinket.io. I do not see how to replace values in a multidimensional array several layers in, regardless of the method. Here is an example:

a = numpy.array([1,2,3])
a[0] = 0

print a

a = numpy.array([[1,2,3],[1,2,3]])
a[0][0] = a[1][0] = 0

print a

Result:

array([0, 2, 3], '<class 'int'>')
array([[1, 2, 3], [1, 2, 3]], '<class 'int'>')

I need the ability to change individual values, my specific code being:

a = numpy.empty(shape = (8,8,2),dtype = str)

for row in range(a.shape[0]):
  for column in range(a.shape[1]):
    a[row][column][1] = 'a'

Thank you for your time and any help provided.

2
  • Your code works for me and prints the expected results [0 2 3] and [[0 2 3], [0 2 3]]. What version of Python and numpy are you using? Commented May 4, 2016 at 14:09
  • An unspecified version of python 2 and numpy on trinket.io, trinket.io/library/trinkets/create?lang=python Commented May 4, 2016 at 15:14

2 Answers 2

1

To change individual values you can simply do something like:

a[1,2] = 'b'

If you want to change all the array, you can do:

a[:,:] = 'c'

Use commas (array[a,b]) instead of (array[a][b])

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately this results in a ValueError being raised if I just try to access the value with your method, ex: import numpy a = numpy.empty(shape = (8,8,2),dtype = str) print a[0,0,0] Result: ValueError: Tuple must contain values for all dimensions on line 5 in main.py
0

With numpy version 1.11.0, I get

[[0 2 3]
 [0 2 3]]

When I run your code. I guess your numpy version is newer and better.

As user3408085 said, the correct thing is to go a[0,0] = 0 to change one element or a[:,0]=0 if your actually want to zero the entire first column.

The reason a[0][0]=0 does not modify a (at least in your version of numpy) is that a[0] is a new array. If break down your command a[0][0]=0 into 2 lines:

b=a[0]
b[0]=0

Then the fact that this modifies a is counterintuitive.

1 Comment

a[0] is a view of the first row of matrix a. It is not copied, and I don't think this has been the case for any numpy version. You can check this easily with c = a[0]; c[1] = 99; print a

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.