eng2019
eng2019

Reputation: 1035

Append array to each element of other array in python

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

Upvotes: 0

Views: 96

Answers (2)

Muftawo Omar
Muftawo Omar

Reputation: 68

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

Upvotes: 0

mozway
mozway

Reputation: 260620

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

Upvotes: 3

Related Questions