@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]
expansion_method[i] = x[:, np.newaxis][i]
two_index_method[5]
scalar_element_method[5]
expansion_method[5]
x[5] = 42
x
two_index_method[5], scalar_element_method[5], expansion_method[5]
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().
source
share