1

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]])

3 Answers 3

3

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]])
Sign up to request clarification or add additional context in comments.

Comments

1

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]])

Comments

0

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])))

Comments

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.