【问题标题】:Is there a way to compose two matrix of numbers in one matrix of text?有没有办法在一个文本矩阵中组合两个数字矩阵?
【发布时间】:2015-04-14 06:24:39
【问题描述】:

我想在 python 中将两个数字矩阵组合成一个格式化文本矩阵。

有什么简单的方法吗?

我可以使用for,但我只是想要这个,因为它更适合工作。

举个简单的例子:

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

array([[0, 0, 0],
       [1, 1, 1],
       [2, 2, 2],
       [3, 3, 3],
       [4, 4, 4]])

到

array([['0:0', '1:0', '2:0'],
       ['0:1', '1:1', '2:1'],
       ['0:2', '1:2', '2:2'],
       ['0:3', '1:3', '2:3'],
       ['0:4', '1:4', '2:4']])

【问题讨论】:

    标签: python arrays matrix


    【解决方案1】:

    您可以使用 np.dstack 来组合两个数组,并使用带有理解的字符串操作来操作组合数组的每个单元格

    >>> arr = np.dstack((arr1, arr2))
    >>> np.array([np.array([':'.join(map(str,cell)) for cell in row ]) for row in arr])
    array([['0:0', '1:0', '2:0'],
           ['0:1', '1:1', '2:1'],
           ['0:2', '1:2', '2:2'],
           ['0:3', '1:3', '2:3'],
           ['0:4', '1:4', '2:4']], 
          dtype='|S3')
    

    【讨论】:

      【解决方案2】:

      您可以使用nditer 来遍历数组,并根据需要制作字符串:例如

      import numpy as np
      
      a1 = np.array([[0, 1, 2],
             [0, 1, 2],
             [0, 1, 2],
             [0, 1, 2],
             [0, 1, 2]])
      
      a2 = np.array([[0, 0, 0],
             [1, 1, 1],
             [2, 2, 2],
             [3, 3, 3],
             [4, 4, 4]])
      
      out=np.empty(a1.shape, dtype='S5')
      
      for x,y,o in np.nditer([a1, a2, out], op_flags=['readwrite']):
          o[...] = "{}:{}".format(x,y)
      
      
      print(out)    
      

      结果:

      [['0:0' '1:0' '2:0']
       ['0:1' '1:1' '2:1']
       ['0:2' '1:2' '2:2']
       ['0:3' '1:3' '2:3']
       ['0:4' '1:4' '2:4']]
      

      【讨论】:

        【解决方案3】:

        使用列表推导和 zip() 形成一个新数组:

        from numpy import array
        
        ar1 = array([[0, 1, 2],
               [0, 1, 2],
               [0, 1, 2],
               [0, 1, 2],
               [0, 1, 2]])
        
        ar2 = array([[0, 0, 0],
               [1, 1, 1],
               [2, 2, 2],
               [3, 3, 3],
               [4, 4, 4]])
        
        res = array([['%s:%s' % (j1, j2) for j1, j2 in zip(i1, i2)] for i1, i2 in zip(ar1, ar2)])
        print(res)
        

        结果:

        [['0:0' '1:0' '2:0']
         ['0:1' '1:1' '2:1']
         ['0:2' '1:2' '2:2']
         ['0:3' '1:3' '2:3']
         ['0:4' '1:4' '2:4']]
        

        此解决方案也适用于通常的 Python 二维列表(只需删除“数组”函数)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-26
          • 1970-01-01
          • 2023-03-09
          • 2018-09-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多