NumPy: array assignment issue when using custom dtype

I found the following perplexity in NumPy and custom dtype for ndarray:

import numpy as np # Make a custom dtype with a single triplet of floats (my actual dtype has other # components, but this suffices to demonstrate the problem. dt = np.dtype([('a', np.float64, 3)]) # Make a zero array with this dtype: points = np.zeros((4, 4), dtype=dt) # Try to edit an entry: points[0][0]['a'] = np.array([1, 1, 1]) print points[0][0]['a'] 

Now it returns as containing not [1. 1. 1.], as expected, but instead [1. 0. 0.], performing only the assignment of the first coordinate. I can get around this by doing the assignment coordinatewise, but this seems unnecessary given that the full assignment should certainly be the default in this case.

Any thoughts on what's going on here?

+6
source share
2 answers

There are many ways to assign points if you want your method to work:

 points[0][0]['a'][:] = np.array([1, 1, 1]) 

or

 points[0,0]['a'][:] = np.array([1, 1, 1]) 

because the points [0,0] ['a'] is an array, if you want to change the contents of the array, you use the index index.

+2
source

If you change the order of the indices, for example: points['a'][0][0] = np.array([1, 1, 1]) , it works fine for me (python 2.6.5, numpy 1.3.0 on Ubuntu 10.04). I would like to know why.

+3
source

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


All Articles