Form a big 2d array from multiple smaller 2d arrays

前端 未结 5 669
囚心锁ツ
囚心锁ツ 2020-12-01 02:44

The question is the inverse of this question. I\'m looking for a generic method to from the original big array from small arrays:

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


        
5条回答
  •  醉酒成梦
    2020-12-01 02:58

    Here is a solution that one can use if someone is wishing to create tiles of a matrix:

    from itertools import product
    import numpy as np
    def tiles(arr, nrows, ncols):
        """
        If arr is a 2D array, the returned list contains nrowsXncols numpy arrays
        with each array preserving the "physical" layout of arr.
    
        When the array shape (rows, cols) are not divisible by (nrows, ncols) then
        some of the array dimensions can change according to numpy.array_split.
    
        """
        rows, cols = arr.shape
        col_arr = np.array_split(range(cols), ncols)
        row_arr = np.array_split(range(rows), nrows)
        return [arr[r[0]: r[-1]+1, c[0]: c[-1]+1]
                         for r, c in product(row_arr, col_arr)]
    

提交回复
热议问题