python - Numpy:根据数组索引设置每一列的一个特定元素

标签 python arrays numpy scipy

与我需要的规模相比,这里是我想要做的事情的一个例子:

>>> a
array([[  21,   22,   23,   24,   25,   26,   27],
       [  56,   57,   58,   59,   60,   61,   62],
       [  14,   15,   16,   17,   18,   19,   20],
       [   7,    8,    9, 1010,   11,   12,   13],
       [  42,   43,   44,   45,   46,   47,   48],
       [  63,   64,   65,   66,   67,   68,   69],
       [   0,    1,    2,    3,    4,    5,    6],
       [  49,   50,   51,   52,   53,   54,   55],
       [  28,   29,   30,   31,   32,   33,   34],
       [  35,   36,   37,   38,   39,   40,   41]])
>>> indices = a.argmax(axis=0)
>>> indices
array([5, 5, 5, 3, 5, 5, 5])
>>> b = np.zeros(a.shape)
>>> b[indices] = 1.0
>>> b # below is the actual output, not what I want
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  1.,  1.,  1.,  1.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]])

但我真正需要的是:

>>> b
array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  0.,  1.,  1.,  1.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.]])

Numpy 索引可能会变得极其复杂,将以上内容用语言表达起来有点困难,所以希望有人能理解我在寻找什么。本质上,它是在一列的最大值处设置一个 1,在其他地方设置零。我该怎么做呢?

最佳答案

来自docs :

If the number of objects in the selection tuple is less than N , then : is assumed for any subsequent dimensions.

在你的选择中只有一个数组,所以你从索引中得到的每一行都等于 1。为了克服这个问题,你需要列索引。我想这可以解决问题:

b[indices, np.arange(a.shape[1])] = 1.0

关于python - Numpy:根据数组索引设置每一列的一个特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29816117/

相关文章:

python - Tensorflow 在使用 tf.device ('/cpu:0' 时分配 GPU 内存)

c# - httpclient post嵌套字典

c - 在 C 中传递结构的一部分

python - 使用 pip freeze 安装 numpy

python - 如何用numpy读取二进制文件的一部分?

python - 获取 BLAST 结果的前 10 个序列 Bio Python

python - 如何检查 BigQuery 查询结果何时返回零记录?

python - 以任意顺序对查询集进行排序

javascript - 使用默认函数扩展 JavaScript 对象

python - numpy 中的小计