python - 生成 生成 numpy 数组

标签 python list numpy numpy-ndarray

我正在尝试使用下面的代码生成一组数组。我也会尝试解释我所做的事情

第一:

example = np.zeros(8,dtype=int)
print(example)

这给了我输出: [0 0 0 0 0 0 0 0]

然后:

input=np.array([],int)
for i in range(0,8):
  if i <8:
    example[i-1]=0
    example[i]=1
    print(example)
  input = np.append(input,example)
print(input)

然后给了我:

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

最后我做到了 输入 = np.append(输入,示例) 这给了我: [1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1] 但这就是我想要的:

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

或者类似的东西。现在,我尝试搜索,无论我尝试什么,我都会遇到错误。希望我尽快得到结果。

最佳答案

如果我正确理解你的问题,你正在寻找单位矩阵。

    X = np.identity(8, dtype=int)

关于python - 生成 生成 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64623453/

相关文章:

python - 带有Q和多个类别的django查询

python - 在 python 中保持格式的同时将字符串列表转换为整数

python - 在列表中添加元组元素

python - 如果它出现在纯 numpy 中的另一个数组中,则有效地删除数组的每一行

python-2.7 - 为什么链式(间隔)比较不适用于 numpy 数组?

python - TensorFlow/TFLearn -架构错误 - 'ValueError: Cannot feed value of shape (64,) for Tensor u' TargetsData/Y : 0', which has shape ' (?,1)'

python - 在任务之间复制 contextvars.Context

python - 如何让 flask 使用 docker 主机安装正确重新加载?

python - 在遍历python列表的同时修改元素时,这种行为背后的原因是什么?

Python TypeError : list indices must be integers or slices, 不是元组