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
  • 12,250
  • 2
  • 39
  • 53
finethen
  • 343
  • 3
  • 14

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
  • 3,964
  • 10
  • 21
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,152
  • 2
  • 9
  • 32
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
  • 94,180
  • 52
  • 233
  • 338
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']]
>>> 
Solen'ya
  • 490
  • 4
  • 11