简体   繁体   中英

Padding a numpy array with zeros, and using another array as an index for ones

I'm trying to pad a numpy array, and I cannot seem to find the right approach from the documentation for numpy. I have an array:

a = array([2, 1, 3, 5, 7])

This represents the index for an array I wish to create. So at index value 2 or 1 or 3 etc I would like to have a one in the array, and everywhere else in the target array, to be padded with zeros. Sort of like an array mask. I would also like to specify the overall length of the target array, l . So my ideal function would like something like:

>>> foo(a,l)
array([0,1,1,1,0,1,0,1,0,0,0]

, where l=10 for the above example.

EDIT:

So I wrote this function:

def padwithones(a,l) :
    p = np.zeros(l)
    for i in a :
        p = np.insert(p,i,1)
    return p

Which gives:

Out[19]: 
array([ 0.,  1.,  0.,  1.,  1.,  1.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.])

Which isn't correct!

What you're looking for is basically a one-hot array:

def onehot(foo, l):
    a = np.zeros(l, dtype=np.int32)
    a[foo] = 1
    return a

Example:

In [126]: onehot([2, 1, 3, 5, 7], 10)
Out[126]: array([0,  1,  1,  1,  0,  1,  0,  1,  0,  0])

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