Web制作、Web開発の歩き方

初心者のためのDjango入門

■第12話:Numpy配列の作成と操作

(最終更新日:2023.06.04)

Djangoフレームワークのイメージ
この記事は5分で読めます!
(絵が小さい場合はスマホを横に)

「NumPy配列を作成しよう!」

前回、NumPyを使うための環境構築と、arrayメソッドによる1,2,3次元のNumPy配列の作成方法を説明した。 今回は、arrayだけでなく、他のメソッドによる配列の作成方法を紹介するとともに、追加、削除といった配列の操作方法を紹介する。 超高速な配列操作ができるNumPyの基本的な操作方法を学んでいこう。


1.NumPy配列の初期化

前回、np.arrayを用いて、多次元のNumPy配列を作成できることを説明した。 今回はまず、NumPy配列の初期化方法について説明する。

NumPy配列の初期化

NumPy配列の初期化

上から順番に説明すると、一番上はzerosメソッドで3×3のNumPy配列をゼロで初期化している。 2番目は、任意の数値(7)で初期化している。 初期化する理由としては、一般的に行われる未定義値混入のリスク回避や、 先にNumPyの形状を決めておきたい場合(プレースホルダとしての役割)である。

次に、等間隔なNumPy配列の作成方法を示す。

等間隔な値での作成

等間隔な値での作成

上のarrangeは0~10までの値を2刻みで埋めるNumPy配列を作成している。 下のlinspaceは0~1の値を5分割、等間隔で埋めるNumPy配列を作成している。

このようなNumPy配列を用意する理由としては、座標軸の範囲やステップ(目盛)の指定や、 比較用としての数値(線形的な値から実測値がどれだけズレているかの確認)、 シミュレーション用の値(理想値を入れた場合のアルゴリズムの計算結果確認)などが挙げられる。 DeepLearningなどの数学的計算、データ処理、統計処理を行ったことがない人はピンと来ないかもしれないが、 まずは便利な比較値、模擬値で使えるという認識で良いと思う。

2.NumPy配列の属性

NumPyには、次元数をはじめとして各属性が存在する。 それらについて、簡単に学んでおこう。下記に各属性値の確認方法を示す。

NumPy配列の各属性

NumPy配列の各属性

上から順番に、ndimはNumPy配列の次元数を返す。 次のshapeは2次元で要素数3の配列という形状を示している。 3番目のsizeは、全ての次元を足した要素数を返す。 最後のdtypeはNumPy配列のデータ型を示す。 NumPy配列に関する情報を得たい場合は、これらの属性が役に立つ。 ただし、これらは値を返す属性で、配列の作成に関しては前項の初期化で作成するか、規則的な値でNumPy配列を作成するか 直接値を指定して行う。

3.NumPy配列の基本的な操作

NumPy配列はPythonのリストと同様に操作することも可能だが、さらに高度な操作も用意している。 ここでは、インデックスとスライスについて説明する。

様々なNumPy配列

様々なNumPy配列

最初のインデックスでは、その要素に対応する値を取得することができる。 arr1[0]はarr1の最初の要素なので1を示し、arr2[1,1]は2番目の配列の2つ目の要素を指定しているので、5を表示する。 次のスライスでは、arr1[1:3]は2番目の要素から3番目の要素まで取得している。 (要素は1番目を0として数える。そのため1は2番目の要素となる。 また、末尾は3なので4番目を指定しているが、その1つ前の3番目までを取得する仕様になっている。) そして、arr2[0:2, 0:2]は、最初の配列から1番目の要素から2番目の要素を、2つ目の配列から1番目の要素から2番目の要素を取得している。 特別な関数を使わず、括弧と数値で指定するだけで、このような高度な操作が可能である。


4.NumPy配列の変形

本項の最後に、NumPy配列の変形について説明する。配列の形状を変更するには、reshapeメソッドを使用する。 reshape(2, 5)は2次元で5個の要素の配列に変更している。そのため、0~4と5~9の2つの配列で再構成されている。 ここで注意すべきは、reshapeは元の配列を変更せず、新たな配列を作成している。 もし、元の配列を変更したい場合は、resizeメソッドを用いれば、それが可能である。 加えて、reshapeやresizeで配列の形状を変更する場合は、変形前後で総要素数が同じになるようにしよう。 総要素数が異なる場合は、エラーが出て、処理を行うことができない。

様々なNumPy配列

様々なNumPy配列

加えて、NumPy配列には転置という処理がある。転置は行と列を入れ替える操作だ。 下記のようにT属性を使用し、2×3のNumPy配列を3×2の配列に入れ替えている。 転置の数学的な意味自体は線形代数の教科書に任せるとして、これらの積で内積(ある方向の仕事量)を表現できるということに留める。

NumPy配列の転置

NumPy配列の転置

5.まとめ

今回、NumPy配列の基本的な操作や変形方法について説明した。 Pythonの配列操作と共通する部分もあるが、中で行っている処理が異なるため、基本的には別物だと思っておこう。 同じデータ型しか組み込めないというのも、Pythonのlistとは大きく異なる点だ。

基本的な操作ではあるが、DeepLearningなどの応用で用いるのも、このような操作と計算処理である。 まずは、今回紹介した基礎を身に着けよう。


▼参考図書、サイト

転置行列の意味・重要な7つの性質と証明  高校数学の美しい物語
Pythonプログラミング入門 5-3. NumPyライブラリ  東京大学 数理・情報教育研究センター


Introduction to Django for Beginners ■ Episode 12: Creating and Manipulating NumPy Arrays (Last updated: 2023.06.04) Image of Django Framework You can read this in 5 minutes! (Turn your smartphone sideways if the image looks small) "Let’s create NumPy arrays!" In the previous article, we explained how to set up the environment to use NumPy and how to create 1D, 2D, and 3D arrays using the `array` method. In this article, we’ll introduce other ways to create arrays, as well as how to add and remove elements. Let's learn the basic operations of NumPy, which enables super-fast array manipulation. [Table of Contents] Initializing NumPy Arrays Attributes of NumPy Arrays Basic Operations on NumPy Arrays Reshaping NumPy Arrays Summary 1. Initializing NumPy Arrays Previously, we introduced how to create multidimensional NumPy arrays using `np.array`. Now, let’s look at other ways to initialize arrays. Initializing NumPy Arrays Initializing NumPy Arrays From the top, the first example uses the `zeros` method to initialize a 3×3 array with zeros. The second initializes the array with a custom value (7). Initializing arrays helps avoid issues with undefined values and allows you to define the shape beforehand, acting as a placeholder. Next, we look at how to create arrays with evenly spaced values. Creating Evenly Spaced Values Creating Evenly Spaced Values The `arange` function creates values from 0 to 10 with steps of 2. The `linspace` function creates 5 evenly spaced values between 0 and 1. These are useful for defining coordinate axes, comparison with real data, or simulations using ideal values. Even if you're unfamiliar with data processing, just think of them as useful mock or reference values. 2. Attributes of NumPy Arrays NumPy arrays have several attributes, including the number of dimensions. Let’s look at how to inspect them. Array Attributes Array Attributes From the top: `ndim` returns the number of dimensions; `shape` shows the dimensions and size of the array; `size` gives the total number of elements; `dtype` indicates the data type of the array. These are useful for inspecting arrays but not for creating them—you’ll use initialization methods for that. 3. Basic Operations on NumPy Arrays NumPy arrays can be manipulated similarly to Python lists, but they also support more advanced operations. Here, we introduce indexing and slicing. Array Indexing and Slicing Array Indexing and Slicing Indexing allows you to access specific elements. For example, `arr1[0]` returns the first element (1), and `arr2[1,1]` returns the value at the second row, second column (5). With slicing: `arr1[1:3]` retrieves the second to third elements. Indexing starts at 0. `arr2[0:2, 0:2]` gets a 2×2 section from the top-left corner. These powerful operations are accessible using simple syntax without special functions. 4. Reshaping NumPy Arrays Lastly, let’s look at reshaping arrays. Use the `reshape` method to change the shape. For example, `reshape(2, 5)` creates a 2D array with two rows of five elements. Note that `reshape` returns a new array without modifying the original. To change the original, use `resize`. Ensure that the total number of elements remains the same after reshaping—otherwise, an error occurs. Reshaping Arrays Reshaping Arrays Additionally, NumPy supports transposing, which swaps rows and columns. You can use the `T` attribute to transpose a 2×3 array into a 3×2 array. While the mathematical meaning is covered in linear algebra, for now, just know it's useful for calculations like dot products. Transposing Arrays Transposing Arrays 5. Summary We’ve covered basic operations and reshaping of NumPy arrays. Although they may resemble Python lists, NumPy arrays behave differently behind the scenes. Notably, they only allow elements of the same data type. These basic operations are fundamental to advanced applications like Deep Learning. Mastering these basics will give you a solid foundation for more complex topics. ▼Reference Books & Sites   Meaning and Key Properties of Transpose Matrices (in Japanese)   Introduction to Python Programming: 5-3 NumPy Library (University of Tokyo)