Suppose I have an array a
representing 3 center points of 3 rectangles. I want to create four other copied points based on each of points in array a
by add 1
or minus 1
in x, y coordinates like shown in the picture.
a = np.arange(9).reshape(3,3)
>>>a
>>>out:[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]]
I'm very new to numpy. What I can think of is that I can make 4 coupies of a
, for the first do a[:,0] =1
, then a[:,1] =1
. for the second do a[:,0] =1
,then a[:,1]-=1
.for the third do a[:,0]-=1
then a[:,1] =1
, for the fourth do a[:,0]-=1
then a[:,1]-=1
. But I know it's stupid. So I 'm wondering if there is a clearer way to do it in numpy?
CodePudding user response:
it seems that what you need is to loop over a Cartesian product, there are many ways of doing so, one is to use itertools, here goes:
import numpy as np
import itertools
a = np.arange(9).reshape(3,3)
list_of_arrays = []
for seq in itertools.product([1, -1], repeat=2):
b = a.copy()
b[:,0] =seq[0]
b[:,1] =seq[1]
list_of_arrays.append(b)
list_of_arrays:
[array([[1, 2, 2], [4, 5, 5], [7, 8, 8]]), array([[1, 0, 2], [4, 3, 5], [7, 6, 8]]), array([[-1, 2, 2], [ 2, 5, 5], [ 5, 8, 8]]), array([[-1, 0, 2], [ 2, 3, 5], [ 5, 6, 8]])]
CodePudding user response:
Using numpy broadcasting:
import itertools
import numpy as np
a = np.arange(9).reshape(3, 3)
shifts = np.array([(dx, dy, 0) for dx, dy in itertools.product([1, -1], repeat=2)])
shifted_a = a shifts[:, None]