2

I made some numpy array np3

np1 = np.array(range(2*3*5))
np3 = np1.reshape(2,3,5)

and np3 has shape like this:

[[[ 0  1  2  3  4]
[ 5  6  7  8  9]
[10 11 12 13 14]]

[[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]]]

then, I made new numpy array np_55

np_55 = np.full((3,1),55)

and np_55 has shape like this:

[[55]
 [55]
 [55]]

I want make numpy array like below using both numpy arrays np3 and np_55 (I'll call that 'ANSWER'):

[[[ 0  1  2  3  4 55]
  [ 5  6  7  8  9 55]
  [10 11 12 13 14 55]]

 [[15 16 17 18 19 55]
  [20 21 22 23 24 55]
  [25 26 27 28 29 55]]]

but I can't make it using both numpy arrays np3 and np_55. Of course I can make hard code like this:

  a = np.append((np3[0]), np3_55, axis=1)
  b = np.append((np3[1]), np3_55, axis=1) 

  a = a.reshape(1,3,6)
  b = b.reshape(1,3,6)

  np.append(a, b, axis=0)

but I don't know how can I solve ANSWER simply.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
LegasLee
  • 51
  • 3
  • For a start, I'd suggest staying away from `np.append`. WIth `axis` all it does is call `np.concatenate`. Learn to use that directly. But to join a (2,3,5) and a (3,1), and get a (2,3,6), you will need to make the latter into a (2,3,1). There's no way around that. – hpaulj Jan 12 '22 at 02:04
  • Instead of concatenate, you could create a (2,3,6). Copy `np3` to [:,:,:5] part of it, and the other to the [:,:,-1]. That's a (2,3,1) space, and with broadcasting a (3,1) will fit. – hpaulj Jan 12 '22 at 02:07
  • Maybe I should add that none of the `concatenate` family of functions (`append`, `stack`, etc) replicates values. Nor does `reshape`. You want two copies of your `np3_55` in the result, so something else has to do the repeat. – hpaulj Jan 12 '22 at 02:43

1 Answers1

0

You can try the following:

import numpy as np

a = np.arange(2*3*5).reshape(2, 3, 5)
b = np.full((3,1),55)

np.c_[a, np.broadcast_to(b, (a.shape[0], *b.shape))]

It gives:

array([[[ 0,  1,  2,  3,  4, 55],
        [ 5,  6,  7,  8,  9, 55],
        [10, 11, 12, 13, 14, 55]],

       [[15, 16, 17, 18, 19, 55],
        [20, 21, 22, 23, 24, 55],
        [25, 26, 27, 28, 29, 55]]])
bb1
  • 7,174
  • 2
  • 8
  • 23