Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat NumPy array without replicating data?

Tags:

I'd like to create a 1D NumPy array that would consist of 1000 back-to-back repetitions of another 1D array, without replicating the data 1000 times.

Is it possible?

If it helps, I intend to treat both arrays as immutable.

like image 972
NPE Avatar asked Apr 06 '11 09:04

NPE


People also ask

How do you repeat an array in NumPy?

NumPy: repeat() function The repeat() function is used to repeat elements of an array. Input array. The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.

What does the repeat function do in NumPy?

The NumPy repeat function essentially repeats the numbers inside of an array. It repeats the individual elements of an array.

How do you copy a NumPy array?

Use numpy. copy() function to copy Python NumPy array (ndarray) to another array. This method takes the array you wanted to copy as an argument and returns an array copy of the given object. The copy owns the data and any changes made to the copy will not affect the original array.


1 Answers

You can't do this; a NumPy array must have a consistent stride along each dimension, while your strides would need to go one way most of the time but sometimes jump backwards.

The closest you can get is either a 1000-row 2D array where every row is a view of your first array, or a flatiter object, which behaves kind of like a 1D array. (flatiters support iteration and indexing, but you can't take views of them; all indexing makes a copy.)

Setup:

import numpy as np a = np.arange(10) 

2D view:

b = np.lib.stride_tricks.as_strided(a, (1000, a.size), (0, a.itemsize)) 

flatiter object:

c = b.flat 
like image 163
Paul Avatar answered Sep 19 '22 00:09

Paul