1

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!

3
  • have you tried anything? Maybe using np.zeros and then indexed assignment...?? Commented Jan 3, 2017 at 18:14
  • so use a generator maybe to determine when a one is to inserted into the np.zeros array? Commented Jan 3, 2017 at 18:18
  • 1
    No. just array_of_zeroes[a] = 1 Commented Jan 3, 2017 at 18:20

1 Answer 1

2

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])
Sign up to request clarification or add additional context in comments.

2 Comments

that's great. Thanks!
If you usedtype=bool it would take 1/4th the space.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.