0

The question was answered by @QuangHoang in the comments. Using np.tile(array, (repeats, 1)) or slower: np.vstack([array]*repeats).

I have what seems to be a simple problem. I have a NumPy array I want to replicate column-wise, and keep it a 2D array, just repeated over and over again say 50x. I try with a np.repeat but the order isn't preserved - it just copies each row however many times I specify. broadcast_to I can't seem to get to work either. I'm thinking maybe I need to flatten the array with a .reshape(-1) then do something with it and reshape it back, but I can't seem to find the right commands. I know I can do it with .append and a for loop, but I'm looking for a vectorized solution. Here's an example with the initial array and then what it should look like afterwards (I'm only repeating it 3x due to space):

array = np.array([(1.00,    0.80,   0.95,   0.88,   0.97,   0.85),
(0.80,  1.00,   0.87,   0.97,   0.80,   0.92),
(0.95,  0.87,   1.00,   0.85,   0.92,   0.89),
(0.88,  0.97,   0.85,   1.00,   0.85,   0.95),
(0.97,  0.80,   0.92,   0.85,   1.00,   0.88),
(0.85,  0.92,   0.89,   0.95,   0.88,   1.00)])

Repeat 3x:

array([[1.  , 0.8 , 0.95, 0.88, 0.97, 0.85],
   [0.8 , 1.  , 0.87, 0.97, 0.8 , 0.92],
   [0.95, 0.87, 1.  , 0.85, 0.92, 0.89],
   [0.88, 0.97, 0.85, 1.  , 0.85, 0.95],
   [0.97, 0.8 , 0.92, 0.85, 1.  , 0.88],
   [0.85, 0.92, 0.89, 0.95, 0.88, 1.  ],
   [1.  , 0.8 , 0.95, 0.88, 0.97, 0.85],
   [0.8 , 1.  , 0.87, 0.97, 0.8 , 0.92],
   [0.95, 0.87, 1.  , 0.85, 0.92, 0.89],
   [0.88, 0.97, 0.85, 1.  , 0.85, 0.95],
   [0.97, 0.8 , 0.92, 0.85, 1.  , 0.88],
   [0.85, 0.92, 0.89, 0.95, 0.88, 1.  ],
   [1.  , 0.8 , 0.95, 0.88, 0.97, 0.85],
   [0.8 , 1.  , 0.87, 0.97, 0.8 , 0.92],
   [0.95, 0.87, 1.  , 0.85, 0.92, 0.89],
   [0.88, 0.97, 0.85, 1.  , 0.85, 0.95],
   [0.97, 0.8 , 0.92, 0.85, 1.  , 0.88],
   [0.85, 0.92, 0.89, 0.95, 0.88, 1.  ]])

Appreciate the help!

6
  • 1
    np.tile(array, (3,1)) or np.vstack([array]*3). Commented Apr 11, 2022 at 18:12
  • Thanks @QuangHoang please post it as an answer so I can accept it! Thanks for the 2nd option too as I use Pythran to compile code and my options for broadcasting are limited. Commented Apr 11, 2022 at 18:18
  • Does this answer your question? Python: Concatenate (or clone) a numpy array N times Commented Apr 11, 2022 at 18:20
  • @Ali_Sh that only works for repeating a 1D array... Commented Apr 11, 2022 at 19:09
  • 1
    I was waiting for him to post an answer so I could accept it, but he hasn't posted yet - @Ali_Sh Commented Apr 11, 2022 at 20:21

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.