python - 根据其索引初始化 NumPy 数组

标签 python python-3.x numpy matrix python-itertools

我正在使用 NumPy 创建几个多维数组并根据索引对它们进行初始化,如下所示:

pos_data = []
# Some typical values
d = 2  # Could also be 3
vol_ext = (1000, 500)  # If d = 3, this will have another entry
ratio = [5.0, 8.0]  # Again, if d = 3, it will have another entry

for i in range(d):
    pos_data.append(np.zeros(vol_ext))

if d == 2:
    for y in range(vol_ext[1]):
        for x in range(vol_ext[0]):
            pos_data[0][x, y] = (x - 1.0) * ratio[0]
            pos_data[1][x, y] = (y - 1.0) * ratio[1]
elif d == 3:
    for z in range(vol_ext[2]):
        for y in range(vol_ext[1]):
            for x in range(vol_ext[0]):
                pos_data[0][x, y, z] = (x - 1.0) * ratio[0]
                pos_data[1][x, y, z] = (y - 1.0) * ratio[1]
                pos_data[2][x, y, z] = (z - 1.0) * ratio[2]

循环有点难看,也很慢。此外,如果我有一个 3 维对象,那么我必须有另一个嵌套循环。

我想知道是否有一种 Pythonic 方式来生成这些值,因为它们仅基于 x、y 和 z 索引。我尝试使用 itertools 中的组合位,但无法使其工作。

最佳答案

使用 np.meshgrid 很容易:

pos_data = np.meshgrid(*(r * (np.arange(s) - 1.0)
                         for s, r in zip(vol_ext, ratio)), indexing='ij')

关于python - 根据其索引初始化 NumPy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49451568/

相关文章:

python - 如何将列表附加到空的 numpy 数组

python - 通过 osmnx 从图中获取特定节点 id

python - 查找列表中子列表项最大值的最佳方法

python-3.x - 使用表情符号肤色修饰符标记句子或推文

python - 由于在 Mac OS X 上 brew install gcc 后缺少 fortran 编译器,仍然无法安装 scipy

python - 使用 scipy 的各种稀疏矩阵乘积的性能

python - 对 xarray 对象重新采样以降低空间分辨率

python - 在 Windows 上使用 Pip Python 安装 TensorFlow

python - 如何在 tkinter 中创建模态对话框?

python - 即使 path.exists() 返回 true,Subprocess.run() 也找不到文件