【问题标题】:Placing all row pairs in 2d numpy array into a 3d array将 2d numpy 数组中的所有行对放入 3d 数组
【发布时间】:2023-01-08 03:07:05
【问题描述】:

考虑显示的 numpy 二维数组:

a = [[8, 16, 4, 1, 0, 5],
     [3, 0, 0, 11, 9, 7],
     [5, 5, 8, 5, 15, 5],
     [2, 0, 2, 14, 2, 0],
     [0, 1, 2, 3, 4, 15]]

我想找到所有行对从数组中,将它们放入 3d 数组中。选择行对时,允许重复行,2 行的顺序并不重要。 在这个例子中,有 15 个这样的 2 行排列,所以我希望得到一个 15 层深的 3d 数组:

     [[8, 16, 4, 1, 0, 5],
      [8, 16, 4, 1, 0, 5]],
     [[8, 16, 4, 1, 0, 5],
      [3, 0, 0, 11, 9, 7]],
     [[8, 16, 4, 1, 0, 5],
      [5, 5, 8, 5, 15, 5]],
...etc
     [[2, 0, 2, 14, 2, 0],
      [2, 0, 2, 14, 2, 0]],
     [[2, 0, 2, 14, 2, 0],
      [0, 1, 2, 3, 4, 15]],
     [[0, 1, 2, 3, 4, 15],
      [0, 1, 2, 3, 4, 15]]]

实际的起始数组可能非常大,所以我希望可以提出一个有效的解决方案。

【问题讨论】:

  • 你为什么需要这个?您的问题可能有更好的解决方案 -

标签: numpy


【解决方案1】:

我认为你必须走出numpy才能获得所有对,例如使用标准库中的itertools.combinations_with_replacement。例子:

import itertools
import numpy as np

a = [[8, 16, 4, 1, 0, 5],
     [3, 0, 0, 11, 9, 7],
     [5, 5, 8, 5, 15, 5],
     [2, 0, 2, 14, 2, 0],
     [0, 1, 2, 3, 4, 15]]

out = np.array(list(itertools.combinations_with_replacement(a, 2)))

【讨论】:

    【解决方案2】:

    您可以使用 itertools.combinations_with_replacement 生成对,然后切片:

    from itertools import combinations_with_replacement
    
    N = 2
    idx = np.array(list(combinations_with_replacement(range(a.shape[0]), r=N)))
    out = a[idx]
    

    输出:

    array([[[ 8, 16,  4,  1,  0,  5],
            [ 8, 16,  4,  1,  0,  5]],
    
           [[ 8, 16,  4,  1,  0,  5],
            [ 3,  0,  0, 11,  9,  7]],
    
           [[ 8, 16,  4,  1,  0,  5],
            [ 5,  5,  8,  5, 15,  5]],
    
           [[ 8, 16,  4,  1,  0,  5],
            [ 2,  0,  2, 14,  2,  0]],
    
           [[ 8, 16,  4,  1,  0,  5],
            [ 0,  1,  2,  3,  4, 15]],
    
           [[ 3,  0,  0, 11,  9,  7],
            [ 3,  0,  0, 11,  9,  7]],
    
           [[ 3,  0,  0, 11,  9,  7],
            [ 5,  5,  8,  5, 15,  5]],
    
           [[ 3,  0,  0, 11,  9,  7],
            [ 2,  0,  2, 14,  2,  0]],
    
           [[ 3,  0,  0, 11,  9,  7],
            [ 0,  1,  2,  3,  4, 15]],
    
           [[ 5,  5,  8,  5, 15,  5],
            [ 5,  5,  8,  5, 15,  5]],
    
           [[ 5,  5,  8,  5, 15,  5],
            [ 2,  0,  2, 14,  2,  0]],
    
           [[ 5,  5,  8,  5, 15,  5],
            [ 0,  1,  2,  3,  4, 15]],
    
           [[ 2,  0,  2, 14,  2,  0],
            [ 2,  0,  2, 14,  2,  0]],
    
           [[ 2,  0,  2, 14,  2,  0],
            [ 0,  1,  2,  3,  4, 15]],
    
           [[ 0,  1,  2,  3,  4, 15],
            [ 0,  1,  2,  3,  4, 15]]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 2016-06-01
      • 2017-09-18
      • 2020-04-04
      • 2019-10-31
      • 2012-12-09
      相关资源
      最近更新 更多