Home > Blockchain >  Generate (NxN) array from (Nx1) array in Python
Generate (NxN) array from (Nx1) array in Python

Time:10-19

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]]

CodePudding user response:

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]])

CodePudding user response:

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.

CodePudding user response:

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?

  • Related