1

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.

1
  • Please take a look at the help or documentation. The signature is numpy.append(arr, values, axis=None), so you need an array arr, the values values you want to append to arr and optionally the axis. Commented May 16, 2019 at 6:38

3 Answers 3

1

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]])
Sign up to request clarification or add additional context in comments.

Comments

0

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]])

Comments

0
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.