Reputation: 391
I have two different arrays b0 and b1 where: b0=[1,2] b1=[3,4]
I want list[1st element of b0, 1st element of b1] to appended into new array B and similarly: list[2nd element of b0, 2nd element of b1] to appended into new array B and so on......
that is my new array should be something like: array([1,3],[2,4])
Below is my code:
b0=np.array([1,2])
b1=np.array([3,4])
for val in range(len(b1)):
L=[b0[val],b1[val]]
B=np.append(L,axis=0)
print(B)
I am getting missing on positional argument values error. Kindly help me to fix it.
Upvotes: 1
Views: 2386
Reputation: 231325
In [51]: b0=np.array([1,2])
...: b1=np.array([3,4])
Order's wrong:
In [56]: np.vstack((b0,b1))
Out[56]:
array([[1, 2],
[3, 4]])
but you can transpose it:
In [57]: np.vstack((b0,b1)).T
Out[57]:
array([[1, 3],
[2, 4]])
stack
is a more general purpose concatenator
In [58]: np.stack((b0,b1), axis=1)
Out[58]:
array([[1, 3],
[2, 4]])
or with:
In [59]: np.column_stack((b0,b1))
Out[59]:
array([[1, 3],
[2, 4]])
More details on combining arrays in my other recent answer: https://stackoverflow.com/a/56159553/901925
All these, including np.append
use np.concatenate
, just tweaking the dimensions in different ways first. np.append
is often misused. It isn't a list append clone. None should be used repeatedly in a loop. They make a new array each time, which isn't very efficient.
Upvotes: 0
Reputation: 717
Using np.append here isn't the most convenient way in my opinion. You can always cast python list into np.array and it's much easier to just use zip in this case.
b0=np.array([1,2])
b1=np.array([3,4])
B=np.array(list(zip(b0,b1)))
output:
>>> B
array([[1, 3],
[2, 4]])
Upvotes: 0
Reputation: 942
If you insist to use numpy array, this is what I would do.
new = []
for x, y in zip(b0, b1):
new.append([x, y])
new = np.array(new)
Or list comprehension
new = np.array([[x,y] for x, y in zip(b0, b1)])
Result:
array([[1, 3],
[2, 4]])
Upvotes: 1