Reputation: 433
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.
Upvotes: 0
Views: 917
Reputation: 96937
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')
Upvotes: 0
Reputation: 13387
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']]
Upvotes: 1
Reputation:
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']]
>>>
Upvotes: 0
Reputation: 4586
>>> 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')
Upvotes: 1