在numpy中内置函数,将Integer解释为具有index = integer值的numpy数组

时间:2015-03-05 19:48:10

标签: python numpy

我是numpy的新手,我试图避免for循环。我的要求如下:

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

另一个例子:

Input = 6
Output = 00010 00000

注意:我不希望二进制表示为3.我只需要设置array = integer的索引值。

numpy中是否有标准库函数?类似于pandas模块中get_dummies函数的东西。

2 个答案:

答案 0 :(得分:2)

试试这个。这并没有使用任何for循环,如果你添加一些健全性检查,它应该可以正常工作。

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

答案 1 :(得分:0)

您是否正在寻找能够执行以下操作的标准功能:

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.]

这更像是对代码的评论而不是答案。只是想明确你要找的是什么,因为我不确定你指定的这个功能是否存在。