Reference to one element of a numpy array

Let's say I have a numpy array like

x = np.arange(10)

can somehow create a link to one element ie

y = create_a_reference_to(x[3])
y = 100 
print x
[  0   1   2 100   4   5   6   7   8   9]
+4
source share
3 answers

You cannot create a link to a single element, but you can get a view on this single element:

>>> x=numpy.arange(10)
>>> y=a[3:4]
>>> y[0]=100
>>> x
array([0, 1, 2, 100, 4, 5, 6, 7, 8, 9])

The reason you cannot do the first is because everything in python is a link. By doing so y = 100, you are changing what indicates y, not the value.

, , . , , python - .

+6

, , .

numpy numpy.ndarray. numpy.ndarray.item, " Python ".

, numpy , numpy numpy.

, , , . , : numpy , ?

+2

@goncalopp , , .

, , , :

x = np.arange(10)
two_index_method = [None] * 10
scalar_element_method = [None] * 10
expansion_method = [None] * 10
for i in range(10):
    two_index_method[i] = x[i:i+1]
    scalar_element_method[i] = x[..., i]  # x[i, ...] works, too
    expansion_method[i] = x[:, np.newaxis][i]  # np.newaxis == None

two_index_method[5]  # Returns a length 1 numpy.ndarray, shape=(1,)
# >>> array([5])
scalar_element_method[5]  # Returns a numpy scalar, shape = ()
# >>> array(5)
expansion_method[5]  # Returns a length 1 numpy.ndarray, shape=(1,)
# >>> array([5])
x[5] = 42  # Change the value in the original `ndarray`
x
# >>> array([0, 1, 2, 3, 4, 42, 6, 7, 8, 9])  # The element has been updated
# All methods presented here are correspondingly updated:
two_index_method[5], scalar_element_method[5], expansion_method[5]
# >>> (array([42]), array(42), array([42]))

scalar_element_method , , ndarray element[0], IndexError. ndarray, element[()] , numpy. -1 ndarray, , -1 ndarray . , element.item(), ( ), , ndarray ndarray:

scalar_element_method[5][0]  # This fails
# >>> IndexError: too many indices for array
scalar_element_method[5][()]  # This works for scalar `ndarray`s
# >>> 42
scalar_element_method[5][()] = 6
expansion_method[5][0]  # This works for length-1 `ndarray`s
# >>> 6
expansion_method[5][()]  # Doesn't return a python scalar (or even a numpy scalar)
# >>> array([6])
expansion_method[5][()] = 8  # But can still be used to change the value by reference
scalar_element_method[5].item()  # item() works to dereference all methods
# >>> 8
expansion_method[5].item()
# >>> [i]8

TL; DR; You can create a singleton view vwith v = x[i:i+1], v = x[..., i]or v = x[:, None][i]. While different settings and getters work with each method, you can always assign values ​​with v[()]=new_value, and you can always get a python scalar with v.item().

0
source

Source: https://habr.com/ru/post/1540514/


All Articles