python - How do I group elements of a numpy array by two? -
i facing following problem. have np.array, of following structure:
[a, b, c, d, e, f] where a..f numpy arrays, guaranteed of same size. hoping achieve following shape:
[ | b, c | d, e | f ] where a | b np.hstack([a, b]). able generalize number of elements in hstack, given number divides length of array.
i not sure how achieve - there nice solution, experience doesn't lead me there. appreciate insight.
a manual way compose numpy array out of smaller blocks use np.block or np.bmat:
h, w, n = 3, 4, 6 a, b, c, d, e, f = [np.full((h,w), i) in list('abcdef')] result = np.block([[a, b], [c, d], [e, f]]) yields
array([['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b'], ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b'], ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b'], ['c', 'c', 'c', 'c', 'd', 'd', 'd', 'd'], ['c', 'c', 'c', 'c', 'd', 'd', 'd', 'd'], ['c', 'c', 'c', 'c', 'd', 'd', 'd', 'd'], ['e', 'e', 'e', 'e', 'f', 'f', 'f', 'f'], ['e', 'e', 'e', 'e', 'f', 'f', 'f', 'f'], ['e', 'e', 'e', 'e', 'f', 'f', 'f', 'f']], dtype='<u1') assuming blocks 2d arrays, more automated way reshape numpy array of blocks use unblockshaped:
import numpy np def unblockshaped(arr, h, w): """ http://stackoverflow.com/a/16873755/190597 (unutbu) return array of shape (h, w) h * w = arr.size if arr of shape (n, nrows, ncols), n sublocks of shape (nrows, ncols), returned array preserves "physical" layout of sublocks. """ n, nrows, ncols = arr.shape return (arr.reshape(h // nrows, -1, nrows, ncols) .swapaxes(1, 2) .reshape(h, w)) h, w, n = 3, 4, 6 arr = np.array([np.full((h,w), i) in list('abcdef')]) result = unblockshaped(arr, h*n//2, w*2) print(result) which produces same result.
see this question example of how arrange sequence of images grid.
Comments
Post a Comment