2

I am new to numpy and I am trying to avoid for-loops. My requirement is as below:

Input - decimal value (ex. 3)
Output - Binary numpy array ( = 00000 01000)

Another example :

Input = 6
Output = 00010 00000

Note: I do not want the binary representation of 3. I only need the index value of array = integer to be set.

Is there any standard library function in numpy? Something analogous to get_dummies function in pandas module.

2 Answers 2

2

Try this instead. This doesn't use any for loops and if you add some sanity checks it should work fine.

def oneOfK(label):
    rows = label.shape[0];
    rowsIndex=np.arange(rows,dtype="int")
    oneKLabel = np.zeros((rows,10))
    #oneKLabel = np.zeros((rows,np.max(label)+1))
    oneKLabel[rowsIndex,label.astype(int)]=1
    return oneKLabel
Sign up to request clarification or add additional context in comments.

Comments

0

Are you looking for a standard function that does something like:

import numpy as np

def foo(d, len=10):
    a = np.zeros(len)
    a[len-d-1] = 1
    return a

print foo(3)  # [ 0.  0.  0.  0.  0.  0.  1.  0.  0.  0.]
print foo(6)  # [ 0.  0.  0.  1.  0.  0.  0.  0.  0.  0.]

This is more of a comment with code than an answer. Just trying to be clear about what you're looking for, because I'm not sure this function exists as you specify.

1 Comment

If you do np.zeros(len, dtype='bool'), this will give a boolean array.

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.