0

Consider the following (Nx1) array:

a = [[1]
     [2]
     [3]
     [4]
     [5]]

How to generate an (NxN) array from a? For e.g. N = 5:

a = [[1 1 1 1 1]
     [2 2 2 2 2]
     [3 3 3 3 3]
     [4 4 4 4 4]
     [5 5 5 5 5]]

3 Answers 3

3

If you want to copy the values, you can use np.repeat:

>>> np.repeat(a, len(a), 1)
array([[1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3],
       [4, 4, 4, 4, 4],
       [5, 5, 5, 5, 5]])

Else, you should perform a broadcast and wrap a with a view using np.broadcast_to:

>>> np.broadcast_to(a, (len(a),)*2)
array([[1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3],
       [4, 4, 4, 4, 4],
       [5, 5, 5, 5, 5]])
Sign up to request clarification or add additional context in comments.

Comments

2

You can do it like this:

a = [[1], [2], [3], [4], [5]]
out = []
for el in a:
    out.append(el * len(a))
return out

It is even better if you compute the length of the 'a' list once at the beginning.

Comments

0

A pythonic one liner to generate the two dimensional array

a = [[1], [2], [3], [4], [5]]
N = 5
x = [i * N for i in a]

Sources:

Python List Comprehensions

How can I define multidimensional arrays in python?

Comments

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.