Reputation: 291
I have two arrays, that I am trying to combine using concatenate:
a = np.array(([1,2], [5,6], [9,10]))
b = np.array(([3,4], [7,8], [11,12], [13,14], [17,18]))
c = np.concatenate((a,b), 1)
This wont work because the lengths of the arrays are different. Therefore I am using len to compare the lengths of the two arrays and then determine the length for c based on the minimum length:
alength = len(a)
blength = len(b)
lengthforc = min(alength, blength)
In this example the minimum lengthforc
is 3. Therefore I am trying an if statement to reduce the length of b by deleting the last two rows(elements).
if blength > lengthforc:
rowstoremove = blength - lengthforc
How can I modify this if statement to carry out what I want (as the number of rows to remove will change), unless there is another way?. The final array should be:
>>> print c
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
Upvotes: 1
Views: 157
Reputation: 85442
Try hstack
:
a = np.array(([1,2], [5,6], [9,10]))
b = np.array(([3,4], [7,8], [11,12], [13,14], [17,18]))
end = min(a.shape[0], b.shape[0])
np.hstack((a[:end], b[:end]))
Result:
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
EDIT
If you don't need NumPy arrays you can go with lists:
a_list = [[1,2], [5,6], [9,10]]
b_list = [[3,4], [7,8], [11,12], [13,14], [17,18]]
Just one line:
[x + y for x, y in zip(a_list, b_list)]
Result:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
Upvotes: 1
Reputation: 1847
I'm not sure if I got the problem correctly (in my solution I just used lists), but is it just that simple ?
a = [[1,2], [5,6], [9,10]]
b = [[3,4], [7,8], [11,12], [13,14], [17,18]]
c = []
for x,y in zip(a,b):
c.append(x+y)
Upvotes: 0