1

i am new in python and have a basic question:

I have three lists :

a = [1, 2, 3]
b = [2, 4, 5]
c = [5, 7, 8]

What i want is an array that looks something like :

x = np.array([1,2,5],[2,4,7],[5,7,8])

is there some on-line python trick to do this?

4
  • By 3d array, do you mean you want a 3x3 matrix? Commented Oct 23, 2013 at 12:20
  • Do you mean a 2D array? Commented Oct 23, 2013 at 12:20
  • 1
    "I have two numpy arrays in 1d" - Errr, no - you have three Python lists and you probably want a 2D array :) Commented Oct 23, 2013 at 12:20
  • sorry for all the mistakes in defining the lists and arrays and stuff :-/ and thank you all for pointing out :) edited the question in correct format now Commented Oct 23, 2013 at 13:36

3 Answers 3

5
np.vstack((np.array([1,2,3]), np.array([1,2,3]), np.array([1,2,3])))

or even simpler

np.vstack(([1,2,3], [1,2,3], [1,2,3]))
Sign up to request clarification or add additional context in comments.

Comments

4

Another simple way is using .T which transposes the matrix.

import numpy as np

a = [1, 2, 3]
b = [2, 4, 5]
c = [5, 7, 8]

np.array([a,b,c]).T

array([[1, 2, 5],
       [2, 4, 7],
       [3, 5, 8]])

2 Comments

this is very elegant :) i figured out np.array([a,b,c]), but didn't know that we can use .T to find the transpose of it :) thank you for sharing the trick
Glad it helped! Numpy has some great little elegant tricks :)
2

Try zip(a, b, c), e.g, x = np.array(*zip(a, b, c)) Official Docs

3 Comments

When the arrays are large, it is probably faster to use the pure numpy solution with vstack shown by Matti, instead of using the built-in zip.
@BasSwinckels +1 Not a numpy user, but from what I've heard I wouldn't doubt it :)
What can we do for matrix i have r,g,b matrixs I want to concatenate them to get a rgb matrix

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.