Skip to main content
 首页 » 编程设计

python之numpy 中的内置函数将 Integer 解释为具有索引 = 整数值集的 numpy 数组

2024年10月25日12tintown

我是 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 函数。

请您参考如下方法:

试试这个。这不使用任何 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