【问题标题】:Simplest way to create a padded matrix of a list of numpy arrays [duplicate]创建numpy数组列表的填充矩阵的最简单方法[重复]
【发布时间】:2017-05-09 06:38:00
【问题描述】:

我有一个这样的 numpy 数组列表(任何大小):

a = [array(2,3,4), array(2,3), array(2)]

如何用最少的代码行创建一个填充矩阵,填充符号“0”如下:

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

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    一种选择是使用itertools 中的zip_longest,您可以为较短的数组填充零值,直到它们具有与最长数组相同的长度:

    from itertools import zip_longest
    from numpy import array
    
    a = [array([2,3,4]), array([2,3]), array([2])]
    
    array(list(zip(*zip_longest(*a, fillvalue=0))))
    
    #array([[2, 3, 4],
    #       [2, 3, 0],
    #       [2, 0, 0]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-14
      • 2014-09-21
      • 1970-01-01
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多