numpy中的内置函数,用于将整数解释为索引为整数值s的numpy数组

2024-05-06 09:33:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我是numpy的新手,我正在努力避免for循环。我的要求如下:

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

另一个例子:

Input = 6
Output = 00010 00000

注意:我不想要3的二进制表示。我只需要设置array=integer的索引值。你知道吗

numpy中有标准的库函数吗?类似于在pandas模块中获取\u dummies函数的东西。你知道吗


Tags: numpyforinputoutput标准value二进制integer
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

您正在寻找一个标准函数,它可以执行以下操作:

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

与其说这是一个答案,不如说这是一个带有代码的注释。只是想弄清楚你在找什么,因为我不确定这个函数是否存在。你知道吗

相关问题 更多 >