Home > Blockchain >  Make 1D array to 2D array with numpy
Make 1D array to 2D array with numpy

Time:09-30

I want to make this array from

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

to we can say 5x5 matrix, so its gonna be like this

[[1, 2, 3, 4, 5]
2, 3, 4, 5, 0]
3, 4, 5, 0, 0]
4, 5, 0, 0 ,0]
5, 0, 0, 0, 0]]

how its possible to make with numpy ?

CodePudding user response:

With np.add.outer and np.where

import numpy as np

a = [1, 2, 3, 4, 5]
r = np.add.outer(a,a) - 1
np.where(r <= len(a), r, 0)

Output

array([[1, 2, 3, 4, 5],
       [2, 3, 4, 5, 0],
       [3, 4, 5, 0, 0],
       [4, 5, 0, 0, 0],
       [5, 0, 0, 0, 0]])

More general for continuously increasing integer ranges

a = [-2, -1, 0 , 1, 2, 3]
r = np.add.outer(a,a) - np.min(a)
np.where(r <= np.max(a), r, 0)

Output

array([[-2, -1,  0,  1,  2,  3],
       [-1,  0,  1,  2,  3,  0],
       [ 0,  1,  2,  3,  0,  0],
       [ 1,  2,  3,  0,  0,  0],
       [ 2,  3,  0,  0,  0,  0],
       [ 3,  0,  0,  0,  0,  0]])

CodePudding user response:

EDIT: don't use either of these if you want a fast solution.

I'm sure there's something buried in the numpy docs that make this trivial, but it's late, so this is what I came up with:

n = 5  # desired shape
x = np.zeros((n, n), dtype="uint8")
for i in range(n):
    x[np.triu_indices(n, i)] = n - i

Output:

>>> x
array([[5, 4, 3, 2, 1],
       [0, 5, 4, 3, 2],
       [0, 0, 5, 4, 3],
       [0, 0, 0, 5, 4],
       [0, 0, 0, 0, 5]], dtype=uint8)

Now use np.fliplr():

>>> np.fliplr(x)
array([[1, 2, 3, 4, 5],
       [2, 3, 4, 5, 0],
       [3, 4, 5, 0, 0],
       [4, 5, 0, 0, 0],
       [5, 0, 0, 0, 0]], dtype=uint8)

Another solution which generates the off-diagonal indices instead of using np.triu, but still a lot of boilerplate:

n = 5  # desired shape
a = [j for j in range(1, n   1) for i in range(j)]
rows = [i for j in range(1, n   1) for i in range(j)]
cols = [i for j in range(n) for i in range(j, -1, -1)]

x = np.zeros((n, n), dtype="uint8")
x[rows, cols] = a

Output:

>>> x
array([[1, 2, 3, 4, 5],
       [2, 3, 4, 5, 0],
       [3, 4, 5, 0, 0],
       [4, 5, 0, 0, 0],
       [5, 0, 0, 0, 0]], dtype=uint8)

CodePudding user response:

arr = np. array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# Convert 1D array to a 2D numpy array of 2 rows and 3 columns.
arr_2d = np. reshape(arr, (2, 5))
print(arr_2d)

You can use reshape function. Populate the array as your requirement and then use reshape.

  • Related