Tbevans88
Tbevans88

Reputation: 103

Combining two arrays into 1 in Python

I have two arrays: vx and vz (shape() = 14502 x 36)) that I want to combine into one array that contains the velocity vector created from the two components (vx and vz).

V = (vx, vz)

Example:

vx = [(1,2,3),(4,5,6)]
vz = [(-1,-2,-3),(-4,-5,-6)]

I need V to be an array where the shape is the same, but each element contains both the vx and vz data. I'm sure this is basic formatting in Python, but I am having difficulty getting it straightened out.

#Expected outcome: V = [(1,-1) (2,-2) (3,-3); (4,-4) (5,-5) (6,-6)]

Or even simpler: a new array where Column 1 is column 1 from Vx and Column 2 is column 1 from Vz and so on.

#Expected outcome: V = [(1,-1,2,-2,3,-3),(4,-4,5,-5,6,-6)]

Upvotes: 0

Views: 4328

Answers (2)

John Coleman
John Coleman

Reputation: 52008

Seems like a nested list comprehension using 2 zips:

>>> [(x,y) for v,w in zip(vx,vz) for x,y in zip(v,w)]
[(1, -1), (2, -2), (3, -3), (4, -4), (5, -5), (6, -6)]

Upvotes: 2

pacholik
pacholik

Reputation: 8982

Array of vectors in numpy:

>>> import numpy as np
>>> V = np.array([vx, vz]).T      # create numpy array and transpose
>>> V[0, 0]
array([ 1, -1])
>>> V[1, 0]
array([ 2, -2])
>>> V[0, 1]
array([ 4, -4])

Upvotes: 3

Related Questions