1

I have to np.arrays which I need to join in a really weird manner. Unfortunately the shapes are givn, I can neither change output nor input.

frequencies =
 [100. 200.] (2,)

and

values =
 [[1. 2.]
 [3. 4.]
 [5. 6.]
 [7. 8.]] (4, 2)

The required output matrix is:

out =
 [[[100.   1.]
  [200.   2.]]

 [[100.   3.]
  [200.   4.]]

 [[100.   5.]
  [200.   6.]]

 [[100.   7.]
  [200.   8.]]]
out.shape =
 (4, 2, 2)

I just don't have any clue how to solve this problem other than iterating each element in values in for loops ... but I am sure there is a pythonical / numpyical way ;)

flawr
  • 10,814
  • 3
  • 41
  • 71
Michael I.
  • 11
  • 1
  • Well yes, if you want to have an output with shape `(4,2,2)` you need to have two tensors of shape `(4,2)`. Here you have `(4,2)` and `(2,)`. So you are missing something. You can `np.tile` the tensor `(2,)` to have `(4,2)`. And then you can stack them with `np.stack([t1, t2], axis=-1)` – Philippe Remy Feb 22 '23 at 12:38

2 Answers2

0

You can use

out = np.stack([np.broadcast_to(f, v.shape), v], axis=2)

The inner broadcast_to reapeats f to the desired size, and stack concatenates the two resulting arrays along a new dimension.

To efficiently work with numpy and similar libraries, it is really worth learning the concept of broadcasting.

flawr
  • 10,814
  • 3
  • 41
  • 71
0

Another way to take advantage of broadcasting is to fill an array with the desired shape:

In [1]: x=np.array([100,200]); y=np.arange(1,9).reshape(4,2)
   
In [2]: res = np.zeros((4,2,2), x.dtype)

You want to assign values to the 0 and 1 'columns' - on the last dimension. Selecting one we see the shape:

In [3]: res[:,:,0].shape
Out[3]: (4, 2)

A (2,) array will broadcast to that (2,)=>(1,2)=>(4,2), so we can do:

In [4]: res[:,:,0] = x

y has the same (4,2) shape:

In [5]: res[:,:,1] = y

And the result:

In [6]: res
Out[6]: 
array([[[100,   1],
        [200,   2]],

       [[100,   3],
        [200,   4]],

       [[100,   5],
        [200,   6]],

       [[100,   7],
        [200,   8]]])
hpaulj
  • 221,503
  • 14
  • 230
  • 353