python - NumPy 的 : how to fill an array smartly?

标签 python arrays numpy

我想在 numpy 中创建一个 3D 数组,如下所示:

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

有什么好的写法吗?

最佳答案

使用 np.tile :

import numpy as np
a = np.array([0, 1])
my_tiled_array = np.tile(a, (3, 3))

结果:

array([[0, 1, 0, 1, 0, 1],
       [0, 1, 0, 1, 0, 1],
       [0, 1, 0, 1, 0, 1]])

编辑:
正如@DSM 在评论中建议的那样,如果您真的想要一个 3D 数组——我对您的代码示例并不完全清楚——您可以使用:

my_3d_tiled_arr = np.tile(a, (3, 3, 3))

结果:

array([[[0, 1, 0, 1, 0, 1],
        [0, 1, 0, 1, 0, 1],
        [0, 1, 0, 1, 0, 1]],

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

       [[0, 1, 0, 1, 0, 1],
        [0, 1, 0, 1, 0, 1],
        [0, 1, 0, 1, 0, 1]]])

关于python - NumPy 的 : how to fill an array smartly?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9741287/

相关文章:

生成器生成的 Python 3 队列,由多进程消耗

python - tensorflow 自动编码器 : Current implementation does not yet support strides in the batch and depth dimensions

python - 在类的字段上对 dict() 进行排序

arrays - 从 numpy 数组计算峰度?

python - 类内的 Numpy 数组赋值

python - 从 scrapy 导出 csv 文件(不是通过命令行)

javascript - 在 React 中使用对象数组作为 props

字符数组初始化:add NUL at the end

python - Numpy,观察中变量对的频率

python - Python3.4 的 Numba KeyError, `KeyError: "不支持选项 : 'arg_types' "`