Home > Enterprise >  Python array and numpy array combining
Python array and numpy array combining

Time:10-04

import numpy as np

a1 = [1,2,3,4,5]
a2 = [6,7,8,9,10]
sc = np.empty((0, 2))
#sc = np.append(np.array([a1[0],a2[0]]))
#sc = np.append([a1[1],a2[1]])

sc = np.c_([a1],[a2])
#sc = np.array([a1[1],a2[1]])

print(sc)
print(sc[0])

I have tried to merge the two normal arrays but cannot find a way to do so. The desired result is sc[0] = [1 6] and sc[1] = [2 7], etc.. where [1 6] is treated as a single value.

I can see lots of error on trying different methods, is there any other possible method.

CodePudding user response:

I am not 100% sure what you are trying, but this should do the trick:

import numpy as np
a1 = [1, 2, 3, 4, 5]
a2 = [6, 7, 8, 9, 10]
s = np.c_[a1, a2]
>>> s
array([[ 1,  6],
       [ 2,  7],
       [ 3,  8],
       [ 4,  9],
       [ 5, 10]])
>>> s[0]
array([1, 6])

CodePudding user response:

You could use zip to feed the array constructor with the values in the right shape:

import numpy as np

a1 = [1,2,3,4,5]
a2 = [6,7,8,9,10]

sc=np.array([*zip(a1,a2)])

print(sc)
[[ 1  6]
 [ 2  7]
 [ 3  8]
 [ 4  9]
 [ 5 10]]

Or you could use reshape on the concatenation of the two lists:

sc = np.reshape(a1 a2,(-1,2),order="F")
  • Related