user8072140
user8072140

Reputation:

How to change a single value in a NumPy array?

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?

Upvotes: 56

Views: 265675

Answers (2)

smithWEBtek
smithWEBtek

Reputation: 111

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)

Upvotes: 0

Allen Qin
Allen Qin

Reputation: 19947

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]])

Upvotes: 83

Related Questions