56

I want to change a single element of an array. For example, I have:

A = np.array([1,2,3,4],
             [5,6,7,8],
             [9,10,11,12],
             [13,14,15,16])

I want to relace A[2][1] = 10 with A[2][1] = 150. How can I do it?

5
  • 5
    The reason this method isn't working is because what you are technically doing is first returning a new array A[2], and then subsequently accessing element [1] of this array. Always use @Allen's method for assigning a value. Commented May 26, 2017 at 20:45
  • See the documentation on indexing in NumPy. Commented Aug 1, 2020 at 0:10
  • for those coming from other languages that are not... it helps to recall that python is 0 indexed. Commented Feb 3 at 17:46
  • @BradSolomon Are you sure ? When I do y= A[2] and check the base of y, the base is A (suggesting y is view of A) . Similarly, if I do z = A[2 ,:], and check the base of z, I again receive A. It means that both y and z are views (created by A[2] and A[2,:] respectively and changing y or z will change A as well. I think the problem in the question is that array has been declared wrong . It should be declared as list of lists (as theanswer by smithWEBtek suggests). right now, it is just syntax error in array declaration. Commented Jun 4 at 19:51
  • How can we achieve the same effect but change multiple elements' values, such as 9, 10, 11, 12, 13, 14, 15, into -1 in one time? Commented Aug 19 at 3:28

2 Answers 2

85

Is this what you are after? Just index the element and assign a new value.

A[2,1]=150

A
Out[345]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 150, 11, 12],
       [13, 14, 15, 16]])
Sign up to request clarification or add additional context in comments.

3 Comments

Is there a reason that Numpy arrays are referred to with [x,y] rather than [x][y]? Is it just to differentiate them from regular Python arrays?
@JammyDodger A bit late, but numpy "arrays" are represented as a contiguous 1D vector in memory while python "arrays" are just lists. A multidimensional vector in numpy is contiguous while python treats them as a list of lists. Their implementations are different. Python multidimensional lists have no information on their inner lists, thus you must use [x][y].
Confusion may be avoided if this is referred to as [y, x]. Numpy defines array coordinates using C-order indexing, so for 2D data stored in standard raster order, the y coordinate comes first.
1
Original question, is passing 4 arrays:
A = np.array([1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16])
print(A)
TypeError: array() takes from 1 to 2 positional arguments but 4 were given
but expects to access and modify a position within an array of arrays:
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]])
print(a)
and more ideal to use lower case for variable name
a[2][1] = 150
print(a)

Comments