0
1

More than 3 years have passed since last update.

numpy その2

Last updated at Posted at 2020-03-01
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

print(arr)
print(arr.shape)
print(arr.ndim)

print('###############')

arr2 = np.array([1, 2, 3, 4 ,5 ,6])

print(arr2)
print(arr2.shape)
print(arr.ndim)

print('###############')

arr3 = arr2.reshape(3, 2)

print(arr3)
print(arr3.shape)
print(arr3.ndim)

print('###############')

arr3 = arr2.reshape(3, -1)

print(arr3)
print(arr3.shape)
print(arr3.ndim)
実行結果
[[1 2 3]
 [4 5 6]]
(2, 3)
2
###############
[1 2 3 4 5 6]
(6,)
2
###############
[[1 2]
 [3 4]
 [5 6]]
(3, 2)
2
###############
[[1 2]
 [3 4]
 [5 6]]
(3, 2)
2

shpeで(行, 列)という形で形状を取得することができる。
ndimを使えば多次元配列の次元数を取得することができる。

形状を変更するにはreshape()メソッドを使用する。
reshape()の引数に(行, 列)の形で形状を指定する。

reshapeで形状を変更した後の配列と元の配列は要素数が同じである必要がある。
上記の例では配列arr2の要素数が6であるため
arr.reshape((2, 3))でreshapeすることができる。
(2 × 3 = 6となるため)
要素数が異なる場合はValueErrorとなる。

reshapeの引数に3と-1を渡すことで自動的に3×2の配列が生成される。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1