0

I have a 3D array defined and initialized as follows. May I know why the following assignment does not work? Thanks.

import numpy as np
xy = np.array([[(0,0) for _ in np.arange(0,2,0.5)] for _ in np.arange(0,2,0.5)])
xy[(0,0)] = (0,0.5)
print(xy[(0,0)])

Output:

[0 0]

Desired output:

[0 0.5]
dantiston
  • 5,161
  • 2
  • 26
  • 30
trickymaverick
  • 199
  • 1
  • 3
  • 8

2 Answers2

0

Refer to below code:

import numpy as np
xy = np.array([[(0,0) for _ in np.arange(0,2,0.5)] for _ in np.arange(0,2,0.5)]).astype('float')
xy[(0,0)] = (0,0.5)
print(xy[(0,0)])

Output

[0.  0.5]
LOrD_ARaGOrN
  • 3,884
  • 3
  • 27
  • 49
  • I get an error when running this: _ValueError: cannot copy sequence with size 2 to array axis with dimension 4_ – AMC Nov 21 '19 at 04:25
  • @AlexanderCécile check your version may be as I didnt get any error. – LOrD_ARaGOrN Nov 21 '19 at 04:26
  • What version of Python and NumPy are you using? – AMC Nov 21 '19 at 04:32
  • 1
    Instead of using `view`, use `dtype=float` in the array creation directly, or just use `xy = 1. * xy`. You are assigning the view to `xy`, so the original array cannot be accessed by name anymore. Why use `view`in the first place, then? You *can* of course use `xy.view(int)` to get the the original array, if that is what you want. Using `view` here at all is a strange choice, and very confusing. – Jan Christoph Terasa Nov 21 '19 at 06:26
  • To add onto what @JanChristophTerasa said, you could also use the aptly-named [`.astype()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.astype.html) method. – AMC Nov 21 '19 at 06:46
0

Alright, here is a version with proper array creation, assignment, and variable names:

import numpy as np

arr_1 = np.zeros(shape=(4, 4, 2))

arr_1[0, 0] = [0, 0.5]

Output of print(arr_1[0, 0]): [0. 0.5]

AMC
  • 2,642
  • 7
  • 13
  • 35
  • 1
    Why was this downvoted? This answers the question, and fixes the issues of the original code: 1. The array should be created with a float type in the first place, making the `view` unnecessary. 2. The creation of an n-d array of zeros using python list comprehensions instead of `np.zeros` is unreadable. 3. Using tuples for indexing is error prone, and syntactically unnecessary. – Jan Christoph Terasa Nov 21 '19 at 06:22
  • @JanChristophTerasa Thank you... Not only is the list comprehension an unidiomatic mess, I imagine that it is really inefficient. – AMC Nov 21 '19 at 06:41
  • For a (4, 4, 2) array the absolute performance hit should be negligible, unless this is done a million times. – Jan Christoph Terasa Nov 21 '19 at 06:44
  • @JanChristophTerasa It won’t make a difference here, you’re right, as you can imagine it’s really a matter of learning good habits and principles. – AMC Nov 21 '19 at 06:49
  • I wholeheartedly agree, that's why I upvoted your answer. – Jan Christoph Terasa Nov 21 '19 at 06:51