我有一系列的男高音
Tenors = np.array(['10Y', '15Y', '1M', '1Y', '20Y', '2Y', '30Y', '3M', '5Y', '6M', '9M'])
其中 M
代表月份,Y
代表年份。正确排序的顺序(升序)将是
['1M', '3M', '6M', '9M', '1Y', '2Y', '5Y', '10Y', '15Y', '20Y', '30Y']
如何使用 python 和 scipy/numpy 来实现这一点?由于 tenors
源自 pandas
数据帧,因此基于 pandas
的解决方案也可以。
最佳答案
方法 #1 这是一种基于 NumPy 的方法,使用 np.core.defchararray.replace
-
repl = np.core.defchararray.replace
out = Tenors[repl(repl(Tenors,'M','00'),'Y','0000').astype(int).argsort()]
<小时/>
方法 #2 如果您正在使用像 '18M'
这样的字符串,我们需要做更多的工作,就像这样 -
def generic_case_vectorized(Tenors):
# Get shorter names for functions
repl = np.core.defchararray.replace
isalph = np.core.defchararray.isalpha
# Get scaling values
TS1 = Tenors.view('S1')
scale = repl(repl(TS1[isalph(TS1)],'Y','12'),'M','1').astype(int)
# Get the numeric values
vals = repl(repl(Tenors,'M',''),'Y','').astype(int)
# Finally scale numeric values and use sorted indices for sorting input arr
return Tenors[(scale*vals).argsort()]
方法#3这是另一种方法,尽管再次处理一般情况是一种愚蠢的方法 -
def generic_case_loopy(Tenors):
arr = np.array([[i[:-1],i[-1]] for i in Tenors])
return Tenors[(arr[:,0].astype(int)*((arr[:,1]=='Y')*11+1)).argsort()]
示例运行 -
In [84]: Tenors
Out[84]:
array(['10Y', '15Y', '1M', '1Y', '20Y', '2Y', '30Y', '3M', '25M', '5Y',
'6M', '18M'],
dtype='|S3')
In [85]: generic_case_vectorized(Tenors)
Out[85]:
array(['1M', '3M', '6M', '1Y', '18M', '2Y', '25M', '5Y', '10Y', '15Y',
'20Y', '30Y'],
dtype='|S3')
In [86]: generic_case_loopy(Tenors)
Out[86]:
array(['1M', '3M', '6M', '1Y', '18M', '2Y', '25M', '5Y', '10Y', '15Y',
'20Y', '30Y'],
dtype='|S3')
关于python - 以金融符号对期限进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39742758/