Reputation: 143
Suppose I have a Numpy array like so:
[10, 11, 12]
I want to copy it several times to form a new array, but subtract every element by 1 each time I copy, to produce:
[[10 11 12]
[ 9 10 11]
[ 8 9 10]
[ 7 8 9]
[ 6 7 8]
[ 5 6 7]]
This is simple with a list comprehension:
import numpy as np
cycles = 6
a = np.array([10, 11, 12])
a = np.stack([a - i for i in range(cycles)])
However, I was wondering if there's a Numpy command that does this, or a more efficient way that doesn't use a list comprehension. I'm using Python 2.7.
Upvotes: 2
Views: 106
Reputation: 221564
One approach would be with broadcasting
-
a - np.arange(6)[:,None]
Sample run -
In [94]: a
Out[94]: array([10, 11, 12])
In [95]: a - np.arange(6)[:,None]
Out[95]:
array([[10, 11, 12],
[ 9, 10, 11],
[ 8, 9, 10],
[ 7, 8, 9],
[ 6, 7, 8],
[ 5, 6, 7]])
Upvotes: 4