pythonnumpytuples

Tuples index when using Ellipsis in a numpy array


I have a code that loops on tuples indexes:

for _ip in np.ndindex(params_shape):
    ...
    loglik[_ip, ...] = ...

If my tuple is (0, 1), I would like the last line to access loglik[0, 1, ...]. Instead, what it seems to do is accessing loglik[0, ...] then loglike[1, ...].

I tried to convert my tuple in list or numpy array, but nothing changes

How can I modify this behaviour without knowing the size of my tuple ?


Solution

  • You can unpack the tuple, but this needs to be done in another tuple for it to work. In code:

    for _ip in np.ndindex(params_shape):
        ...
        loglik[(*_ip, ...)] = ...
    

    For the specific indexing case you show, Ellipsis is not needed (since it's the last slice). You could just do loglik[_ip], though I am assuming your example is not fully representative of your actual case.