【问题标题】:How to concatenate arrays based on number of pair formula如何根据对数公式连接数组
【发布时间】:2021-05-11 01:17:46
【问题描述】:

我有一些数组。现在,我想根据这个公式 (n*(n-1)/2) 连接这些数组。比如说,我有 3 个数组,我可以使用下面的函数 concatenate,

def concat():
  arrays = get_arrays() # this function returns some arrays
  array1 = array[0].reshape(-1, 1)
  array2 = array[1].reshape(-1, 1)
  array3 = array[2].reshape(-1, 1)

  concate_1_2 = np.concatenate([array1, array2], axis=1)
  concate_1_3 = np.concatenate([array1, array3], axis=1)
  concate_2_3 = np.concatenate([array2, array3], axis=1)

我不需要concate_1_1, concate_2_2 or so on。同样,我不想要concate_2_1 and concate_3_1,因为我已经拥有concate_1_2 and concate_1_3。因为我有 3 个数组,所以根据公式,我得到 3*(3-1)/2 = 3 连接。

现在,问题是,我可以拥有不同数量的数组(不只针对 3 或 4 个固定)。我可以有 10 或 20 个阵列。那我该如何动态解决这个问题(不是手动编写,concate_1_2,concate_1_3,等等)

【问题讨论】:

    标签: arrays python-3.x numpy


    【解决方案1】:

    您可以使用itertools 和combinations。如果您想为 2 个列表进行组合,下面给出了一个简单的示例

    代码

    from itertools import combinations
    list(combinations(["a", "b", "c"], 2))
    

    输出

    [('a', 'b'), ('a', 'c'), ('b', 'c')]
    

    有关更多信息,请参阅here。

    【讨论】:

      【解决方案2】:

      一个可能的解决方案

      import numpy as np;
      
      def concat(array):
        (nR, nC) = array.shape; #Number of rows and columns
        concatenationContainer = np.zeros((int(nR*(nR-1)/2), 2*nC)); #add concatenate_1_2, concatenate_1_3, etc..
        counter = 0; #Index of the concatenationContainer array
      
        for row in range(nR): #For each row
          arrayRow = array[row]; #Obtain the next row
          for nextRow in range(row + 1, nR): #For each row that still wasn't concatenated with arrayRow
            concatenationContainer[counter] = np.append(arrayRow, array[nextRow]); #Concatenate
            counter+=1; #Update counter
      
        return concatenationContainer;
      
      if __name__ == '__main__':
        example = np.zeros((4,4));
        example[1] = 1;
        example[2] = 2;
        example[3] = 3;  
        print(example);
        print(concat(example));
      

      此运行代码例如采用以下矩阵:

      [[0. 0. 0. 0.]
       [1. 1. 1. 1.]
       [2. 2. 2. 2.]
       [3. 3. 3. 3.]]
      

      然后返回

      [[0. 0. 0. 0. 1. 1. 1. 1.]
       [0. 0. 0. 0. 2. 2. 2. 2.]
       [0. 0. 0. 0. 3. 3. 3. 3.]
       [1. 1. 1. 1. 2. 2. 2. 2.]
       [1. 1. 1. 1. 3. 3. 3. 3.]
       [2. 2. 2. 2. 3. 3. 3. 3.]]
      

      【讨论】:

      • 非常感谢。我会在运行我的代码后通知你,并通知你。
      • 好的,再次检查代码我在更新计数器时遇到了错误的缩进(已经修复),并删除了 .reshape(-1,1) 方法,因为它们不是必需的。
      • @Servetti 谢谢。代码按照公式工作,但我需要使用reshape(-1, -1) 和axis=1 按列添加它们。不然我后面的代码就不行了!比如,我想获得[[0, 1],[0,1],[0, 1],[0,1]] 而不是获得[0. 0. 0. 0. 1. 1. 1. 1.]
      猜你喜欢
      • 1970-01-01
      • 2022-01-15
      • 2022-11-16
      • 1970-01-01
      • 2020-12-13
      • 1970-01-01
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多