【问题标题】:Create new array based on the value and shapes of current array根据当前数组的值和形状创建新数组
【发布时间】:2021-02-13 04:30:01
【问题描述】:

假设我有一个包含索引 [2,1,1,2,0] 的数组,我想创建一个 3x5 的新数组,该数组在第一行的索引 2 处的值等于 1,在第二行的索引 1 处行,等等.. 例如:

[[0, 0, 1], #2
 [0, 1, 0], #1
 [0, 1, 0], #1
 [0, 0, 1], #2
 [1, 0, 0]] #0

如何在不使用 for 循环的情况下将此过程矢量化?

【问题讨论】:

  • 您不能直接在 python 中将其作为单个操作执行。这甚至不是有效的 python 语法

标签: python arrays vectorization


【解决方案1】:
import numpy as np

in_index =  [2,1,1,2,0]
len_in_index = len(in_index)
result = np.zeros((len_in_index, 3), dtype=int)
for i in range(len_in_index):
    result[i, in_index[i]] = 1
print(result)

输出:

[[0 0 1]
 [0 1 0]
 [0 1 0]
 [0 0 1]
 [1 0 0]]

【讨论】:

  • 谢谢。但是没有for循环可以做到吗?
猜你喜欢
  • 1970-01-01
  • 2020-07-22
  • 1970-01-01
  • 2020-02-11
  • 1970-01-01
  • 1970-01-01
  • 2022-08-23
  • 1970-01-01
  • 2021-05-03
相关资源
最近更新 更多