Is it possible to create a numpy of any arbitrary data structure, for example tuples? If yes, how do I initialize it without writing it out? (Obviously, I don't want to write out 64 by 64 array)
Asked
Active
Viewed 5,902 times
0
-
A structured array of tuples can be created as https://stackoverflow.com/a/63813720/9698684 too – yatu Sep 09 '20 at 14:43
2 Answers
4
Another way:
value = np.empty((), dtype=object)
value[()] = (0, 0)
a = np.full((64, 64), value, dtype=object)
Some trickery is required here to ensure that numpy does not try to iterate the tuple, hence the initial wrapping in an object array

Eric
- 95,302
- 53
- 242
- 374
-
-
@AlexAzazel: Oops, good catch - missed the dtype. [Eventually, this won't be required](https://github.com/numpy/numpy/blob/v1.11.0/numpy/core/numeric.py#L299-L301) – Eric Nov 22 '16 at 13:03
2
Create an empty array of dtype=object
:
a=np.empty((64,64), dtype=object)
then put tuples (or anything else) in it:
for y in range(64):
for x in range(64):
a[y,x] = (0,0)
The most import thing actually is the dtype=object
, allowing you to put any Python object in it (losing the speed of vectorized operations however).

Thomas Baruchel
- 7,236
- 2
- 27
- 46
-
-
@hpaulj You are right, if all values are to be the same, `a.fill` is convenient. I was focusing more on the `dtype=object` flag in my answer than to the way of filling the array. – Thomas Baruchel Nov 20 '16 at 22:05