Building a tuple containing colons to be used to index a numpy array
<p>I've created a class for dealing with multidimensional data of a specific type. This class has three attributes: A list containing the names of the axes (<strong>self.axisNames</strong>); a dictionary containing the parameter values along each axis (<strong>self.axes</strong>; keyd using the entries in axisNames); and a numpy array containing the data, with a dimension for each axis (<strong>self.intensityArr</strong>).</p>

<p>The class also has functions that dynamically add new axes depending on what I need for a specific case, which makes indexing the intensityArr a tricky proposition. To make indexing better I've started writing a function to build the index I need:</p>

<p>Inside class:</p>

<pre><code>def indexIntensityArr(self,indexSpec):
    # indexSpec is a dictionary containing axisName:indexVal entries (indexVal is an int)
    # I want the function to return a tuple for use in indexing (see below def)
    indexList = []
    for axis in self.axisNames:
        if axis in indexSpec:
            indexList.append(indexSpec[axis])
        else:
            # &lt;do something to add : to index list (tuple)&gt;
    return tuple(indexList)
</code></pre>

<p>Outside class:</p>

<pre><code># ... create an instance of my class called myBlob with 4 dimensions ...

mySpec = {'axis1':10,'axis3':7}
mySlicedArr = myBlob.intensityArr[myBlob.indexIntensityArr(mySpec)]
</code></pre>

<p>I expect the above to result in mySlicedArr being a 2-dimensional array.</p>

<p>What do I need to put in the 'else' clause to get an : (or equivalent) in the tuple I use to index the intensityArr? Is this perhaps a bad way to solve the problem?</p>

<p>Inside indexing <code>[]</code>, a <code>:</code> is translated to a <code>slice</code>, and the whole thing is passed to <code>__getitem__</code> as a tuple</p>

<pre><code>indexList = []
for axis in self.axisNames:
    if axis in indexSpec:
        indexList.append(indexSpec[axis])
    else:
        indexList.append(slice(None))
</code></pre>

<p>There are several <code>numpy</code> functions that use an indexing trick like this - that is build up a tuple of index values and slices.  Or if they need to vary it, they'll start with a list, which can mutate, and convert it to a tuple right before use.  (e.g. <code>np.apply_along_axis</code>)</p>

<p>Yes, the full spec for slice is <code>slice(start, stop, step)</code>, with start and stop optional.  Same as for <code>np.arange</code> or <code>range</code>.  And <code>None</code> is equivalent to the unspecified values in a <code>:</code> expression.</p>

<p>A little custom class in <code>np.lib.index_tricks.py</code> translates the : notation into slices:</p>

<pre><code>In [61]: np.s_[:,:1,0:,::3]
Out[61]: 
(slice(None, None, None),
 slice(None, 1, None),
 slice(0, None, None),
 slice(None, None, 3))
</code></pre>

python arrays numpy