0

I'm hoping to combine two arrays...

a = np.array(["A", "B", "C"])
b = np.array(["1", "2", "3", "4", "5"])

into an array (matrix) similar to this:

[["A", "B", "C", "1"]
 ["A", "B", "C", "2"]
 ["A", "B", "C", "3"]
 ["A", "B", "C", "4"]
 ["A", "B", "C", "5"]]

I've tried a for-loop, but it doesn't seem to work. I'm new to Python, any help will be appreciated. Thanks.

Mykola Zotko
  • 15,583
  • 3
  • 71
  • 73
finethen
  • 385
  • 1
  • 4
  • 19

4 Answers4

1
>>> np.hstack((np.tile(a, (len(b), 1)), b[:, None]))
array([['A', 'B', 'C', '1'],
       ['A', 'B', 'C', '2'],
       ['A', 'B', 'C', '3'],
       ['A', 'B', 'C', '4'],
       ['A', 'B', 'C', '5']], dtype='<U1')
Seb
  • 4,422
  • 14
  • 23
1

This will do the trick:

import numpy as np

a = np.array(["A", "B", "C"])
b = np.array(["1", "2", "3", "4", "5"])

c=np.hstack([np.broadcast_to(a, shape=(len(b), len(a))), b.reshape(-1,1)])

Output:

[['A' 'B' 'C' '1']
 ['A' 'B' 'C' '2']
 ['A' 'B' 'C' '3']
 ['A' 'B' 'C' '4']
 ['A' 'B' 'C' '5']]
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34
0

Perhaps use a Python list comprehension with np.append:

>>> [np.append(a,x) for x in b]
[array(['A', 'B', 'C', '1'],
      dtype='<U1'), array(['A', 'B', 'C', '2'],
      dtype='<U1'), array(['A', 'B', 'C', '3'],
      dtype='<U1'), array(['A', 'B', 'C', '4'],
      dtype='<U1'), array(['A', 'B', 'C', '5'],
      dtype='<U1')]

Depending on what you need, you could wrap that result in np.array:

>>> np.array([np.append(a,x) for x in b])
array([['A', 'B', 'C', '1'],
       ['A', 'B', 'C', '2'],
       ['A', 'B', 'C', '3'],
       ['A', 'B', 'C', '4'],
       ['A', 'B', 'C', '5']],
      dtype='<U1')
Alex Reynolds
  • 95,983
  • 54
  • 240
  • 345
0

One way of doing it would be:

import numpy as np

a = np.array(["A", "B", "C"])
b = np.array(["1", "2", "3", "4", "5"])

output=[]

for i in list(b):
    a_list=list(a)
    a_list.append(i)
    output.append(a_list)

output=np.asarray(output)

print(output)

Result of this is as desired:

[['A' 'B' 'C' '1']
 ['A' 'B' 'C' '2']
 ['A' 'B' 'C' '3']
 ['A' 'B' 'C' '4']
 ['A' 'B' 'C' '5']]
>>> 
McLovin
  • 555
  • 8
  • 20