954,546 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

comine 2 array togetger by column

Hi,

I am newie to python.

How I combine 2 multi-dimension array into one by column?
here is an exmaple:

a = 1 2 3
2 3 4
3 4 5

b = 4 5 6
6 7 8
8 9 1

the combined array should be
c = 1 2 3 4 5 6
2 3 4 6 7 8
3 4 5 8 9 1

So essentially, stack all 3 columns of b into the end of a. c is 3 by 6 array.
How can i do that in python? Thanks in advance.

jliu66
Light Poster
30 posts since Oct 2007
Reputation Points: 10
Solved Threads: 0
 

First off, Python doesn't really have arrays unless you include some of the add on packages. Python uses lists, so I would suggest that you take a look at lists. Combining is a simple matter. You can iterate through the lists with a for loop, creating a new list with the combined pairs. Itertools will also do this but that may be more than you want. Post some code and we'll let you know our opinion on how you can improve it/get it to work.

woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
 

One way to do this is using a high speed list comprehension ...

# combine two 2D lists using a list comprehension
# a list is Python's more flexible array container
 
a = [[1, 2, 3],
[2, 3, 4],
[3, 4, 5]]
 
b = [[4, 5, 6],
[6, 7, 8],
[8, 9, 1]]
 
c = []
c = [a[ix] + b[ix] for ix in range(len(a))]
print c
"""
my output -->
[[1, 2, 3, 4, 5, 6], [2, 3, 4, 6, 7, 8], [3, 4, 5, 8, 9, 1]]
"""


Like woooee says, study up on lists.

vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

One way to do this is using a high speed list comprehension ...

# combine two 2D lists using a list comprehension
# a list is Python's more flexible array container
 
a = [[1, 2, 3],
[2, 3, 4],
[3, 4, 5]]
 
b = [[4, 5, 6],
[6, 7, 8],
[8, 9, 1]]
 
c = []
c = [a[ix] + b[ix] for ix in range(len(a))]
print c
"""
my output -->
[[1, 2, 3, 4, 5, 6], [2, 3, 4, 6, 7, 8], [3, 4, 5, 8, 9, 1]]
"""
Like woooee says, study up on lists.


Thanks so much. That's really neat code. Appreciated.

John

jliu66
Light Poster
30 posts since Oct 2007
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You