Home > database >  Convert one-dimensional array to two-dimensional array so that each element is a row in the result
Convert one-dimensional array to two-dimensional array so that each element is a row in the result

Time:05-25

I want to know how to convert this: array([0, 1, 2, 3, 4, 5]) to this:

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

In short, given a flat array, repeat each element inside the array n times, so that each element creates a sub-array of n of the same element, and concatenate these sub-arrays into one, so that each row contains an element from the original array repeated n times.

I can do this:

def repeat(lst, n):
    return [[e]*n for e in lst]
>repeat(range(10), 4)

[[0, 0, 0, 0],
 [1, 1, 1, 1],
 [2, 2, 2, 2],
 [3, 3, 3, 3],
 [4, 4, 4, 4],
 [5, 5, 5, 5],
 [6, 6, 6, 6],
 [7, 7, 7, 7],
 [8, 8, 8, 8],
 [9, 9, 9, 9]]

How to do this in NumPy?

CodePudding user response:

You can use numpy's repeat like this:

np.repeat(range(10), 4).reshape(10,4) 

which gives:

[[0 0 0 0]
 [1 1 1 1]
 [2 2 2 2]
 [3 3 3 3]
 [4 4 4 4]
 [5 5 5 5]
 [6 6 6 6]
 [7 7 7 7]
 [8 8 8 8]
 [9 9 9 9]]

CodePudding user response:

You can use tile that handles dimensions:

a = np.array([0, 1, 2, 3, 4, 5])
N = 4

np.tile(a[:,None], (1, N))

# or
np.tile(a, (N, 1)).T

or broadcast_to:

np.broadcast_to(a, (N, a.shape[0])).T

# or
np.broadcast_to(a[:,None], (a.shape[0], N))

Or multiply by an array of ones:

a[:,None]*np.ones(N, dtype=a.dtype)

output:

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

CodePudding user response:

You can use this also

import numpy as np

def oned_to_2d(array_length, number_of_value):
    data = np.empty([0,number_of_value])
    for i in range(0,array_length):
        a = np.array(number_of_value*[i])
        data = np.append(data, np.array([a]),axis=0)
    return data

oned_to_2d(4,4)

The output is

array([[0., 0., 0., 0.],
   [1., 1., 1., 1.],
   [2., 2., 2., 2.],
   [3., 3., 3., 3.]])
  • Related