从numpy数组中获取索引

时间:2016-12-27 16:36:33

标签: python arrays indexing

我有以下情况:

我的变量 params 由几个子值组成:

User

但是我只对 ampl freq 感兴趣,它们的值是:

>> params
rec.array([ (12.534214167520581, ... 0.7833572386219857, -0.4215128074913047,  3.717773146160369)], 
      dtype=[('const', '<f8'), ('ampl', '<f8'), ('freq', '<f8'), ('phase', '<f8'), ('e_const', '<f8'), ('e_ampl', '<f8'), ('e_freq', '<f8'), ('e_phase', '<f8'), ('stopcrit', '<f8')])

经过一些分析后,我意识到唯一感兴趣的值是那些 ampl <22>> 22.53421417 和 21.53421417

让我们调用这些值 new_array = [22.53421417,21.53421417] ,我需要的是创建一个新的 params [&#39; ampl&#39;] params [&#39; freq&#39;] 但只有我感兴趣的值,换句话说,减少 params [&#39; ampl&#39;] < / i>和 params [&#39; freq&#39;]

>>params['ampl']
array([ 12.53421417,  22.53421417,  21.53421417, ...,  2.53421417,
    1.53421417,  2.53421417])

>>params['freq']
array([  0.78335724,   1.56697824,   4.86322084, ...,  11.45392432,
    21.17763437,   0.4946571 ])

此外,这些是数据类型:

params['ampl'] = [22.53421417, 21.53421417]
params['freq'] = [1.56697824,   4.86322084]

我使用 .index 尝试了几件事情,但是没有工作。提前感谢任何建议。

1 个答案:

答案 0 :(得分:0)

假设数组的排序使得params['amp'][0]和`params ['freq'] [0]与具有幅度和频率的单个对象相关,我们可以执行以下操作。

imp_amp = [22.53421417, 21.53421417]
for i in imp_amp:
    loc_in_amp = param['amp'].index(i) #get each values location in amp
    values_you_want = param['freq'][loc_in_amp] #grab the frequency for that value
    #do whatever you want with the values.

一个方便的单行,创建一个新的dict,amp:freq。

n_param = {i:param['freq'][param['amp'].index(i)] for i in imp_amp}
print n_param

#   {22.53421417: 1.56697824, 
#    21.53421417: 4.86322084}