note.nkmk.me

Convert numpy.ndarray and list to each other

Posted: 2019-11-06 / Tags: Python, NumPy, List

The NumPy array numpy.ndarray and the Python built-in type list can be converted to each other.

  • Convert list to numpy.ndarray: numpy.array()
  • Convert numpy.ndarray to list: tolist()

For convenience, the term "convert" is used, but in reality, a new object is generated while keeping the original object.

Sponsored Link

Convert list to numpy.ndarray: numpy.array()

By passing list to numpy.array(), numpy.ndarray is generated based on it.

import numpy as np

l_1d = [0, 1, 2]

arr_1d = np.array(l_1d)

print(arr_1d)
print(arr_1d.dtype)
# [0 1 2]
# int64

The data type dtype of generated numpy.ndarray is automatically determined from the original list, but can also be specified with the argument dtype.

arr_1d_f = np.array(l_1d, dtype=float)

print(arr_1d_f)
print(arr_1d_f.dtype)
# [0. 1. 2.]
# float64

The same applies to multi-dimensional arrays of two or more dimensions.

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

arr_2d = np.array(l_2d)

print(arr_2d)
# [[0 1 2]
#  [3 4 5]]

Multi-dimensional list are just nested list (list of list), so it doesn't matter if the number of elements in the list doesn't match.

However, passing it to numpy.array() creates numpy.ndarray whose elements are built-in list.

Note that missing elements cannot be filled.

l_2d_error = [[0, 1, 2], [3, 4]]

arr_2d_error = np.array(l_2d_error)

print(arr_2d_error)
# [list([0, 1, 2]) list([3, 4])]

print(arr_2d_error.dtype)
# object

print(arr_2d_error.shape)
# (2,)

Convert numpy.ndarray to list: tolist()

The method tolist() of numpy.ndarray returns list.

Depending on the number of dimensions of the original numpy.ndarray, a nested list is generated. Each element can be accessed by repeating the index [n].

1D:

arr_1d = np.arange(3)

print(arr_1d)
# [0 1 2]

l_1d = arr_1d.tolist()

print(l_1d)
# [0, 1, 2]

2D:

arr_2d = np.arange(6).reshape((2, 3))

print(arr_2d)
# [[0 1 2]
#  [3 4 5]]

l_2d = arr_2d.tolist()

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

3D:

arr_3d = np.arange(24).reshape((2, 3, 4))

print(arr_3d)
# [[[ 0  1  2  3]
#   [ 4  5  6  7]
#   [ 8  9 10 11]]
#  [[12 13 14 15]
#   [16 17 18 19]
#   [20 21 22 23]]]

l_3d = arr_3d.tolist()

print(l_3d)
# [[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]]

print(l_3d[0])
# [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]

print(l_3d[0][0])
# [0, 1, 2, 3]

print(l_3d[0][0][0])
# 0
Sponsored Link
Share

Related Categories

Related Posts