4,488 views
この記事は最終更新から 1816日 が経過しています。
4行3列の乱数配列aを作成する。
>>> import numpy as np >>> a = np.random.rand(4,3) >>> a array([[ 0.15940847, 0.56564422, 0.82868468], [ 0.55344639, 0.55527501, 0.75242168], [ 0.43876864, 0.50025427, 0.07168502], [ 0.15186 , 0.00686738, 0.98197383]])
配列aを numpy.reshape で 6行2列に変形する。
>>> b = np.reshape(a, (6,2))
>>> b
array([[ 0.15940847, 0.56564422],
[ 0.82868468, 0.55344639],
[ 0.55527501, 0.75242168],
[ 0.43876864, 0.50025427],
[ 0.07168502, 0.15186 ],
[ 0.00686738, 0.98197383]])
配列bの要素の値を書き換える。
>>> b[3,1] = 0
>>> b
array([[ 0.15940847, 0.56564422],
[ 0.82868468, 0.55344639],
[ 0.55527501, 0.75242168],
[ 0.43876864, 0. ],
[ 0.07168502, 0.15186 ],
[ 0.00686738, 0.98197383]])
すると、配列aの要素も書き換わっている!
>>> a
array([[ 0.15940847, 0.56564422, 0.82868468],
[ 0.55344639, 0.55527501, 0.75242168],
[ 0.43876864, 0. , 0.07168502],
[ 0.15186 , 0.00686738, 0.98197383]])
numpy.reshape したものを別のオブジェクトに代入したい場合、numpy.copy を使用する。
>>> a = np.random.rand(4,3) >>> a array([[ 0.59587499, 0.33831817, 0.75324048], [ 0.67519994, 0.57802629, 0.48760045], [ 0.27385989, 0.02654679, 0.46217751], [ 0.20590104, 0.31475441, 0.31250744]]) >>> b = a.reshape(6,2).copy() >>> b array([[ 0.59587499, 0.33831817], [ 0.75324048, 0.67519994], [ 0.57802629, 0.48760045], [ 0.27385989, 0.02654679], [ 0.46217751, 0.20590104], [ 0.31475441, 0.31250744]]) >>> b[3,0] = 0 >>> b array([[ 0.59587499, 0.33831817], [ 0.75324048, 0.67519994], [ 0.57802629, 0.48760045], [ 0. , 0.02654679], [ 0.46217751, 0.20590104], [ 0.31475441, 0.31250744]]) >>> a array([[ 0.59587499, 0.33831817, 0.75324048], [ 0.67519994, 0.57802629, 0.48760045], [ 0.27385989, 0.02654679, 0.46217751], [ 0.20590104, 0.31475441, 0.31250744]])
こう書いても同じ。
>>> a = np.random.rand(4,3) >>> a array([[ 0.59738729, 0.8289699 , 0.22344194], [ 0.86271615, 0.76692546, 0.1131666 ], [ 0.61305503, 0.28302821, 0.24619501], [ 0.10828006, 0.38060943, 0.46060143]]) >>> b = np.copy(a.reshape(6,2)) >>> b array([[ 0.59738729, 0.8289699 ], [ 0.22344194, 0.86271615], [ 0.76692546, 0.1131666 ], [ 0.61305503, 0.28302821], [ 0.24619501, 0.10828006], [ 0.38060943, 0.46060143]]) >>> b[3,0] = 0 >>> b array([[ 0.59738729, 0.8289699 ], [ 0.22344194, 0.86271615], [ 0.76692546, 0.1131666 ], [ 0. , 0.28302821], [ 0.24619501, 0.10828006], [ 0.38060943, 0.46060143]]) >>> a array([[ 0.59738729, 0.8289699 , 0.22344194], [ 0.86271615, 0.76692546, 0.1131666 ], [ 0.61305503, 0.28302821, 0.24619501], [ 0.10828006, 0.38060943, 0.46060143]])