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>To add to hpaulj's answer, you can very simply extend your setup to make it even more generic by using <code>np.s_</code>. The advantage of using this over <code>slice</code> is that you can use <code>numpy</code>'s slice syntax more easily and transparently. For example:</p>

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

<p>(Extra info: <code>np.s_[7:8]</code> retrieves only the 7th column, but it preserves the dimension, i.e. your sliced array will still be 4D with a shape of 1 in that dimension: very useful for broadcasting).</p>

<p>And if you want to use the same syntax in your function definition as well:</p>

<pre><code>indexList = []
for axis in self.axisNames:
    if axis in indexSpec:
        indexList.append(indexSpec[axis])
    else:
        indexList.append(np.s_[:])
return tuple(indexList)
</code></pre>

<p>All of this can be done equally well with <code>slice</code>. You would specify <code>np.s_[10:15]</code> as <code>slice(10, 15)</code>, and <code>np.s_[:]</code> as <code>slice(None)</code>, as hpaulj says.</p>

python arrays numpy