ndarrayの形状変換
ndarrayの形状(shape)を変換する方法です。
「reshape」を用いると既存のndarrayの形状を変換することができます。ただし変換前と変換後の要素数が異なってしまうような変換はできないため、要素の欠落は発生しません。
# -*- coding: utf-8 -*- import numpy na = numpy.array([[1, 10, 100], [2, 20, 200]]) na_reshape = numpy.reshape(na, [3, 2]) print na.shape print na print '-----------------------' print na_reshape.shape print na_reshape # これはエラーとなる # numpy.reshape(na, [1, 1])
--実行結果--
(2L, 3L) [[ 1 10 100] [ 2 20 200]] ----------------------- (3L, 2L) [[ 1 10] [100 2] [ 20 200]]
ndarrayクラスにも「reshape」メソッドが実装されているため、既存のインスタンスから形状変換を行うことも可能です。ただし元のndarrayには影響を与えず、新しい配列を戻り値として返します。
# -*- coding: utf-8 -*- import numpy na = numpy.array([[1, 10, 100], [2, 20, 200]]) na_reshape = na.reshape([3, 2]) print na.shape print na print '-----------------------' print na_reshape.shape print na_reshape
--実行結果--
(2L, 3L) [[ 1 10 100] [ 2 20 200]] ----------------------- (3L, 2L) [[ 1 10] [100 2] [ 20 200]]
「resize」は変換前後で要素数が異なっていても構いません。そのため要素の欠落が発生する場合があります。
# -*- coding: utf-8 -*- import numpy na = numpy.array([[1, 10, 100], [2, 20, 200]]) na_resize = numpy.resize(na, [2, 2]) print na.shape print na print '-----------------------' print na_resize.shape print na_resize
--実行結果--
(2L, 3L) [[ 1 10 100] [ 2 20 200]] ----------------------- (2L, 2L) [[ 1 10] [100 2]]
ndarrayクラスにも「resize」メソッドが実装されているため、既存のインスタンスから形状変換を行うことも可能です。こちらは元のndarrayインスタンスに変更が加わります。
# -*- coding: utf-8 -*- import numpy na = numpy.array([[1, 10, 100], [2, 20, 200]]) print na.shape print na print '-----------------------' na.resize([2, 2]) print na.shape print na
--実行結果--
(2L, 3L) [[ 1 10 100] [ 2 20 200]] ----------------------- (2L, 2L) [[ 1 10] [100 2]]
|
|
|
|
|
|
|
|
||
|
| |||
|
|
|
||
既存配列をリストへ変換!
▶数値解析:ndarrayのリスト変換
