Search code examples
pythonarraysnumpystackconcatenation

Numpy: How to stack a single array into each row of a bigger array and turn it into a 2D array?


I have a numpy array named heartbeats with 100 rows. Each row has 5 elements.

I also have a single array named time_index with 5 elements. I need to prepend the time index to each row of heartbeats.

heartbeats = np.array([
    [-0.58, -0.57, -0.55, -0.39, -0.40],
    [-0.31, -0.31, -0.32, -0.46, -0.46]
])
time_index = np.array([-2, -1, 0, 1, 2])

What I need:

array([-2, -0.58],
      [-1, -0.57],
      [0, -0.55],
      [1, -0.39],
      [2, -0.40],
      [-2, -0.31],
      [-1, -0.31],
      [0, -0.32],
      [1, -0.46],
      [2, -0.46])

I only wrote two rows of heartbeats to illustrate.


Solution

  • Assuming you are using numpy, the exact output array you are looking for can be made by stacking a repeated version of time_index with the raveled version of heartbeats:

    np.stack((np.tile(time_index, len(heartbeats)), heartbeats.ravel()), axis=-1)