Home > database >  Appending two arrays in Python
Appending two arrays in Python

Time:09-06

I am trying to append two numpy arrays A and J[0] using np.concatenate but there is an error. I also present the expected output.

import numpy as np

A=np.array([ 1,  3,  5,  7,  9, 10, 12, 13, 14, 15, 16, 18, 20, 21, 22, 23])

J=[[4, 6, 8, 11, 17, 19]]
J=np.array(J)
T=np.concatenate(A,J[0],axis=1)

The error is

in <module>
    T=np.concatenate(A,J[0],axis=1)

  File "<__array_function__ internals>", line 4, in concatenate

TypeError: concatenate() got multiple values for argument 'axis'

The expected output is

array([ 1,  3,  4, 5,  6, 7,  8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23])

CodePudding user response:

T = np.sort(np.concatenate((A, J[0])))

CodePudding user response:

You don't need axis=1 (Because your two arrays have rank==1). Also you can use numpy.squeeze.

J = np.squeeze(J)
T = np.concatenate((A,J))      # By default 'axis=0'

# Or like your code
# T = np.concatenate((A,J[0])) # By default 'axis=0'

print(T)
# [ 1  3  5  7  9 10 12 13 14 15 16 18 20 21 22 23  4  6  8 11 17 19]

T.sort()
print(T)

Output: [ 1 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]

CodePudding user response:

Use for loops to append everything into a new array.

This should work:

import numpy as np

A=np.array([ 1,  3,  5,  7,  9, 10, 12, 13, 14, 15, 16, 18, 20, 21, 22, 23])

J=[4, 6, 8, 11, 17, 19]
J=np.array(J)

complete_array = []

for i in A:
    complete_array.append(i)
for i in J:
    complete_array.append(i)

print(complete_array)
  • Related