简体   繁体   中英

Retrieving array elements with an array of frequencies in NumPy

I have an array of numbers, a . I have a second array, b , specifying how many times I want to retrieve the corresponding element in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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