0

I have this array:

a = np.array(([11,12,13],[21,22,23],[31,32,33],[41,42,43]))
b = np.array([88,99])

I want to get:

c = np.array(([11,12,13,88,99],[21,22,23,88,99],[31,32,33,88,99],[41,42,43,88,99]))

How can I do that? Thanks

juanpa.arrivillaga
97.7k14 gold badges141 silver badges190 bronze badges
asked Sep 28, 2021 at 17:55

2 Answers 2

3

Assuming you have numpy arrays, you could do:

import numpy as np
np.concatenate([a, np.tile(b, (len(a), 1))], 1)

Or, using numpy.broadcast_to:

np.concatenate([a, np.broadcast_to(b, (len(a), len(b)))], 1)

output:

array([[11, 12, 13, 88, 99],
 [21, 22, 23, 88, 99],
 [31, 32, 33, 88, 99],
 [41, 42, 43, 88, 99]])

solution with lists:

a_list = a.tolist()
b_list = b.tolist()
from itertools import product, chain
[list(chain(*i)) for i in product(a_list, [b_list])]

output:

[[11, 12, 13, 88, 99],
 [21, 22, 23, 88, 99],
 [31, 32, 33, 88, 99],
 [41, 42, 43, 88, 99]]
answered Sep 28, 2021 at 17:59
Sign up to request clarification or add additional context in comments.

4 Comments

np.tile(b, len(a)).reshape(len(a), -1) -> np.tile(b, (len(a), 1))
Yes, of course, silly me ;) Thanks!
also one can use c = [arr_a+b for arr_a in a], if a and b are lists (or converted to lists) :)
@HadarSharvit yes of course, but I love itertools :p
0

You can use NumPy append

import numpy as np
a = np.array(([11,12,13],[21,22,23],[31,32,33],[41,42,43]))
b = np.array([88,99])
c= np.array([np.append(arr, b) for arr in a ])

Output:

array([[11, 12, 13, 88, 99],
 [21, 22, 23, 88, 99],
 [31, 32, 33, 88, 99],
 [41, 42, 43, 88, 99]])
answered Sep 28, 2021 at 18:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.