Home > Software design >  How to append array rowwise in numpy?
How to append array rowwise in numpy?

Time:09-20

I have two numpy arrays:

a = np.array([[0,0,1],
              [0,1,0],
              [0,1,1],
              [1,1,1],
              [1,1,0],
              [0,0,0]])
b = np.array([9,9,9])

What is the easiest way to append array b into each row of array a?

The output should look like this:

c = np.array([[0,0,1,9,9,9],
              [0,1,0,9,9,9],
              [0,1,1,9,9,9],
              [1,1,1,9,9,9],
              [1,1,0,9,9,9],
              [0,0,0,9,9,9]])

CodePudding user response:

One way using broadcast_to and hstack:

c = np.hstack([a, np.broadcast_to(b, (a.shape[0], b.shape[0]))])

output:

array([[0, 0, 1, 9, 9, 9],
       [0, 1, 0, 9, 9, 9],
       [0, 1, 1, 9, 9, 9],
       [1, 1, 1, 9, 9, 9],
       [1, 1, 0, 9, 9, 9],
       [0, 0, 0, 9, 9, 9]])

CodePudding user response:

One way to expand array b and then append to array a

>>> np.append(a, b.repeat(len(a)).reshape((len(a),len(b))), axis=1)

array([[0, 0, 1, 9, 9, 9],
       [0, 1, 0, 9, 9, 9],
       [0, 1, 1, 9, 9, 9],
       [1, 1, 1, 9, 9, 9],
       [1, 1, 0, 9, 9, 9],
       [0, 0, 0, 9, 9, 9]])

CodePudding user response:

Another possible solution, using list comprehension:

np.array([x   b.tolist() for x in a.tolist()])

Output:

array([[0, 0, 1, 9, 9, 9],
       [0, 1, 0, 9, 9, 9],
       [0, 1, 1, 9, 9, 9],
       [1, 1, 1, 9, 9, 9],
       [1, 1, 0, 9, 9, 9],
       [0, 0, 0, 9, 9, 9]])

Yet another possible solution, using numpy.fromiter and chain.from_iterable:

from itertools import chain

(np.fromiter(chain.from_iterable(np.concatenate((x, b)) for x in a), int)
  .reshape((a.shape[0], a.shape[1]   b.shape[0])))
  • Related