简体   繁体   English

创建由依赖于索引的二维数组组成的4-D numpy数组

[英]Creating 4-D numpy array consisting of index-dependent 2-d arrays

I have a 2-D nx2 array where n is a variable as the code runs. 我有一个二维nx2数组,其中n是代码运行时的变量。 Take n=4 for example, the original array is 以n = 4为例,原始数组为

[[0, 1],
 [2, 3],
 [4, 5],
 [6, 7]]

I want to create a 4-D nxnx2x2 array where each element of the top level nxn array is an index-dependent 2x2 array made up of the ith and jth row of the original array. 我想创建一个4-D nxnx2x2数组,其中顶层nxn数组的每个元素是一个依赖于索引的2x2数组,该数组由原始数组的第i行和第j行组成。 For example, at index [0,3] the 2x2 array will be 例如,在索引[0,3]处,2x2数组为

[[0, 1],
 [6, 7]]

I have tried using the np.fromfunction function and construct the 2x2 array at each coordinate. 我尝试使用np.fromfunction函数并在每个坐标处构造2x2数组。

new = np.fromfunction(lambda i,j: np.stack((old[i],old[j])), (n,n), dtype=int)

Instead of getting an nxnx2n2 array, I got a 2xnxnxn instead. 我没有得到nxnx2n2数组,而是得到了2xnxnxn。

Of course, there is the option of using a nested loop and iterating over nxn times but I'd like to do it in a faster way, if possible. 当然,也可以选择使用嵌套循环并循环nxn次,但如果可能的话,我想以更快的方式进行。

Here is an example by using broadcast_arrays() and stack() : 这是使用broadcast_arrays()stack()的示例:

import numpy as np

a = np.array(
    [[0, 1],
     [2, 3],
     [4, 5],
     [6, 7]])

b = np.stack(np.broadcast_arrays(a[:, None, :], a[None, :, :]), axis=-2)
print(b[0, 3])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM