如何在numpy数组中提取值的索引?

时间:2016-12-28 02:03:19

标签: python arrays numpy

以下是该方案:

我有以下变量:

document.addEventListener('DOMContentLoaded', function () {
    restore();
    var allButtons = document.getElementsByClassName('buttons');
    function listenI(i) {
        allButtons[i].addEventListener('click', () => removeMe(i));
    }
    for (var i = 0; i < allButtons.length; i++) {
        listenI(i);
    }
});

function restore() {
    // get the tab link and title
    chrome.storage.local.get({ urlList: [], titleList: [] }, function (data) {
        urlList = data.urlList;
        titleList = data.titleList;

        // add the titles and url's to the DOM
        for (var i = 0, n = urlList.length; i < n; i++) {
            addToDom(urlList[i], titleList[i]);
        }
    });
}

我需要的是检测am = 12.33和am = 15.23的索引,一旦提取(在这种情况下索引是[0]和[3]),我需要创建新的变量:

val = [('am', '<f8'), ('fr', '<f8')] # val is type numpy.recarray     

am = [12.33, 1.22, 5.43, 15.23]  # am is type numpy.ndarray  

fr = [0.11, 1.23, 2.01, 1.01]   # fr is type numpy.ndarray  

我的问题是:有关如何提取索引的想法吗?

我已经使用了 .index np.where 但是因为收到了 .index 的错误消息所以它似乎有问题 - - &GT; &#34; AttributeError:&#39; numpy.ndarray&#39; 对象没有属性 .index &#34;并且对于 np.where ,返回的索引是什么---&gt; &#34; array([],dtype = int64)&#34;

感谢您的任何想法!

1 个答案:

答案 0 :(得分:3)

您可能希望np.in1d返回一个布尔数组,以指示某个元素是否在另一个数组中:

import numpy as np
am = np.array([12.33, 1.22, 5.43, 15.23]) 
fr = np.array([0.11, 1.23, 2.01, 1.01])

index = np.where(np.in1d(am, [12.33, 15.23]))[0]
index
# array([0, 3])

am[index]
# array([ 12.33,  15.23])

fr[index]
# array([ 0.11,  1.01])

或许您有一个包含属性的数组:

new_arr = np.array(zip(am, fr), dtype=val)

index = np.where(np.in1d(new_arr['am'], [12.33, 15.23]))[0]

new_am = new_arr[index]['am']
new_fr = new_arr[index]['fr']

new_am
# array([ 12.33,  15.23])

new_fr
# array([ 0.11,  1.01])