Convert 1D array to 2D array in Python (numpy.ndarray, list)

Modified: | Tags: Python, NumPy, List

This article explains how to convert a one-dimensional array to a two-dimensional array in Python, both for NumPy arrays ndarray and for built-in lists list.

See the following article on how to convert (= flatten) a multi-dimensional array to a one-dimensional array.

Convert a one-dimensional numpy.ndarray to a two-dimensional numpy.ndarray

Use the reshape() method to transform the shape of a NumPy array ndarray. Any shape transformation is possible. This includes but is not limited to transforming from a one-dimensional array to a two-dimensional array.

By using -1, the size of the dimension is automatically calculated.

import numpy as np

a = np.arange(6)
print(a)
# [0 1 2 3 4 5]

print(a.reshape(2, 3))
# [[0 1 2]
#  [3 4 5]]

print(a.reshape(-1, 3))
# [[0 1 2]
#  [3 4 5]]

print(a.reshape(2, -1))
# [[0 1 2]
#  [3 4 5]]

If you specify a shape that does not match the total number of elements in the original array, an error will be raised.

# print(a.reshape(3, 4))
# ValueError: cannot reshape array of size 6 into shape (3,4)

# print(a.reshape(-1, 4))
# ValueError: cannot reshape array of size 6 into shape (4)

Convert a one-dimensional list to a two-dimensional list

With NumPy

With NumPy, you can convert list into numpy.ndarray, transform the shape with reshape(), and then convert it back to list.

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

print(np.array(l).reshape(-1, 3).tolist())
# [[0, 1, 2], [3, 4, 5]]

print(np.array(l).reshape(3, -1).tolist())
# [[0, 1], [2, 3], [4, 5]]

See the following article on how to convert numpy.ndarray and list to each other.

Without NumPy

If NumPy is not available, you can still achieve the transformation using list comprehensions, range(), and slices.

def convert_1d_to_2d(l, cols):
    return [l[i:i + cols] for i in range(0, len(l), cols)]

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

print(convert_1d_to_2d(l, 2))
# [[0, 1], [2, 3], [4, 5]]

print(convert_1d_to_2d(l, 3))
# [[0, 1, 2], [3, 4, 5]]

print(convert_1d_to_2d(l, 4))
# [[0, 1, 2, 3], [4, 5]]

In the function above, the first argument is the original list, and the second argument is the number of elements in the inner list (i.e., the number of columns). If there is a remainder, a list with a different number of elements will be stored, as in the last example.

If you want to specify the number of rows:

def convert_1d_to_2d_rows(l, rows):
    return convert_1d_to_2d(l, len(l) // rows)

print(convert_1d_to_2d_rows(l, 2))
# [[0, 1, 2], [3, 4, 5]]

print(convert_1d_to_2d_rows(l, 3))
# [[0, 1], [2, 3], [4, 5]]

print(convert_1d_to_2d_rows(l, 4))
# [[0], [1], [2], [3], [4], [5]]

The above function is a basic example. If the total number of elements is not divisible by the number of rows you specify, the actual number of rows in the result may differ from what you've specified, as shown in the last example.

Related Categories

Related Articles