简体   繁体   English

在NumPy中使用频率数组检索数组元素

[英]Retrieving array elements with an array of frequencies in NumPy

I have an array of numbers, a . 我有一个数字数组, a I have a second array, b , specifying how many times I want to retrieve the corresponding element in a . 我有第二个数组b ,它指定我要检索a中相应元素a How can this be achieved? 如何做到这一点? The ordering of the output is not important in this case. 在这种情况下,输出的顺序并不重要。

import numpy as np

a = np.arange(5)
b = np.array([1,0,3,2,0])

# desired output = [0,2,2,2,3,3]
# i.e. [a[0], a[2], a[2], a[2], a[3], a[3] ]

那就是np.arange(5).repeat([1,0,3,2,0])所做的。

A really inefficient way to do that is this one : 这样做的一种真正低效的方法是:

import numpy as np

a = np.arange(5)
b = np.array([1,0,3,2,0])

res = []
i = 0
for val in b:
    for aa in range(val):
        res.append(a[i])
    i += 1
print res

here's one way to do it: 这是一种实现方法:

res = []
for i in xrange(len(b)):
    for j in xrange(b[i]):
        out.append(a[i])

res = np.array(res)  # optional

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM