Home > Back-end >  How to change 1d array to 2d array under certain conditions
How to change 1d array to 2d array under certain conditions

Time:02-13

Is there a way through python numpy operations to produce the following result?

Input 1d array :

[3, 0, 0, 2, 2, 1]

Output 2d array :

3 0 0 2 2 1
0 0 0 2 2 1
0 0 0 2 2 1
2 2 2 2 2 1
2 2 2 2 2 1
1 1 1 1 1 1

CodePudding user response:

in addition to jeromie’s brilliant answer, here is a support for unordered array:

indexes = np.arange(len(arr))
idx = np.maximum(indexes[None,:], indexes[:, None])
arr[idx]

CodePudding user response:

Assuming the input array always contains increasing values, you can use np.maximum(arr[None,:], arr[:, None]). This compute the maximum of arr[i] and arr[j] for all items at the location (i, j) of the output array thanks to Numpy broadcasting. If the input does not always contains increasing values, then the out needs to be better defined.

CodePudding user response:

Adir's solution is brilliant and should be accepted.

EDIT: original answer --

It seems that you want to essentially make a matrix by "rotating" a vector like a wiper blade from the top left corner. This produces that pattern:

def wiper_blade_matrix(x):
    n = len(x)
    z = np.zeros((n, n), x.dtype)
    for k in range(-(n - 1), n):
        z[np.where(np.eye(n, k=k))]  = x[abs(k):]
    return z

Usage:

In [4]: wiper_blade_matrix(np.array([0, 0, 0, 1, 1, 2]))
Out[4]:
array([[0, 0, 0, 1, 1, 2],
       [0, 0, 0, 1, 1, 2],
       [0, 0, 0, 1, 1, 2],
       [1, 1, 1, 1, 1, 2],
       [1, 1, 1, 1, 1, 2],
       [2, 2, 2, 2, 2, 2]])

In [5]: wiper_blade_matrix(np.array([0, 0, 0, 5, 1, 2]))
Out[5]:
array([[0, 0, 0, 5, 1, 2],
       [0, 0, 0, 5, 1, 2],
       [0, 0, 0, 5, 1, 2],
       [5, 5, 5, 5, 1, 2],
       [1, 1, 1, 1, 1, 2],
       [2, 2, 2, 2, 2, 2]])

In [6]: wiper_blade_matrix(np.array([3, 0, 0, 2, 2, 1]))
Out[6]:
array([[3, 0, 0, 2, 2, 1],
       [0, 0, 0, 2, 2, 1],
       [0, 0, 0, 2, 2, 1],
       [2, 2, 2, 2, 2, 1],
       [2, 2, 2, 2, 2, 1],
       [1, 1, 1, 1, 1, 1]])
  • Related