Convert any multi-dimensional numpy array to tuple of tuples of tuples… agnostic of number of dimensions

Question:

That this answer to Convert numpy ndarray to tuple of tuples in optimize method doens’t offer anything more than tuple(tuple(i) for i in a[:,0,:]) suggests this doesn’t exist, but I am looking for something like a .totuple() method similar to numpy’s .tolist() in that you don’t need to know the number of dimensions beforehand to generate a tuple of tuples of tuples…

For my needs this would apply to a float or integer numerical array only.

Asked By: uhoh

||

Answers:

You can make use of a recursive function which converts to a tuple independent of the number of dimensions:

def totuple(a):
    try:
        return tuple(totuple(i) for i in a)
    except TypeError:
        return a

Found in this answer:
Convert numpy array to tuple

Answered By: Jelle Westra

A more explicit alternative:

def totuple(a):
    if a.shape == ():
        return a.item()
    else:
        return tuple(map(totuple, a))

Example:

import numpy as np
a = np.arange(3 * 4).reshape(3, 4)
print(totuple(a))
((0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11))
Answered By: user76284