> What do folks think about a totuple() method — even before this I’ve
> wanted that. But in this case, it seems particularly useful.
Two thoughts:
1. `totuple` makes most sense for 2d arrays. But what should it do for
1d or 3+d arrays? I suppose it could make the last dimension a tuple, so
1d arrays would give a list of tuples of size 1.
2. structured array's .tolist() already returns a list of tuples. If we
have a 2d structured array, would it add one more layer of tuples?
That
would raise an exception if read back in by `np.array` with the same dtype.
In [84]: new_full = np.array(full.tolist(), full.dtype)
But this does not:
In [85]: new_full = np.array(tuple(full.tolist()), full.dtype)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-85-c305063184ff> in <module>()
----> 1 new_full = np.array(tuple(full.tolist()), full.dtype)
ValueError: could not assign tuple of length 4 to structure with 2 fields.
These points make me think that instead of a `.totuple` method, this
might be more suitable as a new function in np.lib.recfunctions.
If the
goal is to help manipulate structured arrays, that submodule is
appropriate since it already has other functions do manipulate fields in
similar ways. What about calling it `pack_last_axis`?
def pack_last_axis(arr, names=None):
if arr.names:
return arr
names = names or ['f{}'.format(i) for i in range(arr.shape[-1])]
return arr.view([(n, arr.dtype) for n in names]).squeeze(-1)
Then you could do:
>>> pack_last_axis(uv).tolist()
to get a list of tuples.
In [90]: pack_last_axis(uv)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-90-a75ee44c8401> in <module>()
----> 1 pack_last_axis(uv)
<ipython-input-89-cfbc76779d1f> in pack_last_axis(arr, names)
1 def pack_last_axis(arr, names=None):
----> 2 if arr.names:
3 return arr
4 names = names or ['f{}'.format(i) for i in range(arr.shape[-1])]
5 return arr.view([(n, arr.dtype) for n in names]).squeeze(-1)
AttributeError: 'numpy.ndarray' object has no attribute 'names'
So maybe you meants something like:
In [95]: def pack_last_axis(arr, names=None):
...: try:
...: arr.names
...: return arr
...: except AttributeError:
...: names = names or ['f{}'.format(i) for i in range(arr.shape[-1])]
...: return arr.view([(n, arr.dtype) for n in names]).squeeze(-1)
full = np.array(zip(time, pack_last_axis(uv)), dtype=dt)