Sort tenors in finance notation
<p>I have an array of tenors</p>

<pre><code>Tenors = np.array(['10Y', '15Y', '1M', '1Y', '20Y', '2Y', '30Y', '3M', '5Y', '6M', '9M'])
</code></pre>

<p>where <code>M</code> stands for month and <code>Y</code> stands for years. The correctly sorted order (ascending) would then be</p>

<pre><code>['1M', '3M', '6M', '9M', '1Y', '2Y', '5Y', '10Y', '15Y', '20Y', '30Y']
</code></pre>

<p>How do I achieve that using python with scipy/numpy? As the <code>tenors</code> originate from a <code>pandas</code> dataframe a solution based on <code>pandas</code> would be fine as well.</p>

<p>I opted for the long solution since I needed <code>convert_tenors</code> anyway. This also solves <a href="http://stackoverflow.com/questions/39742758/sort-tenors-in-finance-notation/39752239#comment66797667_39742758">Jim's objection</a>.</p>

<pre><code>import scipy

def convert_tenors(tenors):
    #convert tenors to years
    new_tenors = scipy.zeros_like(tenors,dtype=float)
    for i,o in enumerate(tenors):
        if(o[-1]=='M'):
            new_tenors[i] = int(o[:-1])/12
        else:
            new_tenors[i] = int(o[:-1])
    return new_tenors

def sort_tenors(tenors):
    #sort tenors in ascending order
    idx = scipy.argsort(convert_tenors(tenors))
    return tenors[idx]  

Tenors = scipy.array(['10Y', '15Y', '1M', '1Y', '20Y', '18M', '2Y', '30Y', '3M', '5Y', '6M', '9M'])
print(sort_tenors(Tenors))
</code></pre>

<p>returns</p>

<pre><code>['1M' '3M' '6M' '9M' '1Y' '18M' '2Y' '5Y' '10Y' '15Y' '20Y' '30Y']
</code></pre>

python sorting pandas numpy finance