【问题标题】:python numpy split array into unequal subarrayspython numpy将数组拆分为不相等的子数组
【发布时间】:2012-04-12 22:10:22
【问题描述】:

我正在尝试将一个数组拆分为 n 个部分。有时这些部分大小相同,有时大小不同。

我正在尝试使用:

split = np.split(list, size)

当大小均分到列表中时,这可以正常工作,否则会失败。有没有办法用额外的“少数”元素“填充”最终数组?

【问题讨论】:

    标签: python list numpy split


    【解决方案1】:

    您在寻找 np.array_split 吗? 这是文档字符串:

    Split an array into multiple sub-arrays.
    
    Please refer to the ``split`` documentation.  The only difference
    between these functions is that ``array_split`` allows
    `indices_or_sections` to be an integer that does *not* equally 
    divide the axis.
    
    See Also
    --------
    split : Split array into multiple sub-arrays of equal size.
    
    Examples
    --------
    >>> x = np.arange(8.0)
    >>> np.array_split(x, 3)
        [array([ 0.,  1.,  2.]), array([ 3.,  4.,  5.]), array([ 6.,  7.])]
    

    http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.array_split.html

    【讨论】:

      【解决方案2】:
      def split_padded(a,n):
          padding = (-len(a))%n
          return np.split(np.concatenate((a,np.zeros(padding))),n)
      

      【讨论】:

      • 这个答案是什么?
      【解决方案3】:

      您可以通过将索引作为列表传递来将数组拆分为不相等的块 示例

      **x = np.arange(10)**
      x
      (0,1,2,3,4,5,6,7,8,9)
      np.array_split(x,[4])
      [array([0,1,2,3],dtype = int64),
             array([4,5,6,7,8,9],dtype = int64)**
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-13
        • 1970-01-01
        • 1970-01-01
        • 2017-04-15
        • 1970-01-01
        相关资源
        最近更新 更多