2

I'm trying to to update an element in an array. If I've got an array say:

[[0, 0],
 [0, 0]]

as far as I knew the way to update eg. the first element to 0.5, was

array[0,0] = 0.5

However when I print the array the contents are unchanged. I read some things on Stack Overflow about copies being created of arrays but I don't know if this applies.

Any help would be great

1
  • 1
    I think you'll have to be more specific. Try posting more of your code so we can see the context. Commented Mar 27, 2019 at 19:30

4 Answers 4

3

Your problem is that your array is integer-valued (because you initialize it with integers), and when you write a float to it, it gets rounded to 0. You can check that this is the case if you write

array = np.array([[0, 0], [0, 0]])
array[0, 0] = 1.5
>>> array = array([[1, 0],
                   [0, 0]])

To get the expected behaviour, either initialize it with floats

array = np.array([[0., 0.], [0., 0.]])

or explicitly specify dtype

array = np.array([[0, 0], [0, 0]], dtype=np.float32)
Sign up to request clarification or add additional context in comments.

Comments

1

You need to change the data type of the numpy array before updating the value to float

import numpy as np

a = [[0,0],[0,0]]
a = np.array(a)
a = a.astype('float64')
a[0,0] = 0.5
print(a)

this will give you

[[0.5 0. ]
 [0.  0. ]]

Comments

0

The data type of the array is automatically set to int, 0.5 as an int is 0.

# For example:
In [12]: int(0.5)
Out[12]: 0

# To construct the array try:
array = np.array([[0.0,0.0],[0.0,0.0]])
# or:
array = np.array([[0,0],[0,0]], dtype=float)

Then:

In [9]: array[0,0]=0.5

In [10]: array
Out[10]: 
array([[0.5, 0. ],
       [0. , 0. ]])

Comments

0

Python nested list objects don't support array-like indexing. You can use only a single value to to index a list

arr = [[0,0], [0,0]]
arr[0][0] = 0.5
arr # [[0.5, 0], [0, 0]]

To use the kind of indexing you mention in your post, you'll have to use a numpy array

import numpy as np
np_arr = np.array([[0,0], [0,0]], dtype=np.float32)
np_arr[0,0] = 0.5

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.