Reputation: 178
Is there a way to use sub-arrays of a 1-D array as the input tiles for np.tile
? I start with:
In this case, the number of repeats for each tile is equal to the number of elements in that tile.
Example:
arr = np.array([0,1,2,3,4])
tile_sizes = np.array([2, 3])
num_repeats = tile_sizes
#do some np.tile thing here
and the output array will be:
np.array([0,1,0,1,2,3,4,2,3,4,2,3,4])
note that the first 2
elements (0
and 1
) formed a tile of shape (2,)
which was repeated 2
times. The next tile was 3
elements (2
,3
, and 4
) and was tiled 3
times.
The use-case for this will involve arrays of a million elements, so memory and speed are concerns, meaning broadcasting is preferred.
A non-broadcasting way to achieve this looks like:
tiles = np.split(arr, np.cumsum(tile_sizes)[:-1])
repeated_tiles = [np.tile(tile, tile.shape[0]) for tile in tiles]
output = np.concatenate(repeated_tiles)
output
>>>>>
array([0, 1, 0, 1, 2, 3, 4, 2, 3, 4, 2, 3, 4])
Upvotes: 3
Views: 319
Reputation: 3272
It's not a perfect solution, but you can get rid of the list comprehension using np.repeat
if that helps.
a = np.arange(5)
tile_sizes = np.array([2, 3])
tiles = np.array(np.split(a, np.cumsum(tile_sizes)[:-1]), dtype=np.object)
tiles = np.concatenate(np.repeat(tiles, tile_sizes))
Upvotes: 1