NumPy配列ndarrayの次元数、形状、サイズ(全要素数)を取得
NumPy配列ndarrayの次元数、形状(各次元のサイズ)、サイズ(全要素数)を取得するには、numpy.ndarray
のndim
, shape
, size
属性を使う。組み込み関数len()
では最初の次元の大きさが返される。
目次
1次元から3次元までの以下のnumpy.ndarray
を例とする。
import numpy as np
a_1d = np.arange(3)
print(a_1d)
# [0 1 2]
a_2d = np.arange(12).reshape((3, 4))
print(a_2d)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
a_3d = np.arange(24).reshape((2, 3, 4))
print(a_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]]]
source: numpy_ndim_shape_size.py
NumPy配列ndarrayの次元数: ndim
numpy.ndarray
の次元数はndim
属性で整数値int
として取得できる。
print(a_1d.ndim)
# 1
print(type(a_1d.ndim))
# <class 'int'>
print(a_2d.ndim)
# 2
print(a_3d.ndim)
# 3
source: numpy_ndim_shape_size.py
新たな次元を追加したいときはnumpy.newaxis
やnumpy.expand_dims()
を使う。以下の記事を参照。
NumPy配列ndarrayの形状(各次元のサイズ): shape
numpy.ndarray
の形状(各次元のサイズ)はshape
属性でタプルとして取得できる。
一次元配列の場合も整数値ではなく要素数1のタプルとなる(要素数1のタプルは末尾にカンマがつく)。
print(a_1d.shape)
# (3,)
print(type(a_1d.shape))
# <class 'tuple'>
print(a_2d.shape)
# (3, 4)
print(a_3d.shape)
# (2, 3, 4)
source: numpy_ndim_shape_size.py
例えば二次元配列の場合は(行数, 列数)
となる。行数・列数いずれか一方のみを取得したい場合は、タプルのそれぞれの要素を取得すればOK。
print(a_2d.shape[0])
# 3
print(a_2d.shape[1])
# 4
source: numpy_ndim_shape_size.py
それぞれ別の変数に代入することも可能。
row, col = a_2d.shape
print(row)
# 3
print(col)
# 4
source: numpy_ndim_shape_size.py
形状を変換する場合はreshape()
を使う。以下の記事を参照。
NumPy配列ndarrayのサイズ(全要素数): size
numpy.ndarray
のサイズ(全要素数)はsize
属性で取得できる。
print(a_1d.size)
# 3
print(type(a_1d.size))
# <class 'int'>
print(a_2d.size)
# 12
print(a_3d.size)
# 24
source: numpy_ndim_shape_size.py
NumPy配列ndarrayの最初の次元のサイズ: len()
len()
は、リストの要素数や文字列の文字数を返す組み込み関数。
numpy.ndarray
に対しては最初の次元のサイズ(大きさ)を返す。shape[0]
と等しく、一次元配列の場合に限りsize
とも等しい。
print(len(a_1d))
# 3
print(a_1d.shape[0])
# 3
print(a_1d.size)
# 3
print(len(a_2d))
# 3
print(a_2d.shape[0])
# 3
print(len(a_3d))
# 2
print(a_3d.shape[0])
# 2
source: numpy_ndim_shape_size.py