Web制作、Web開発の歩き方

初心者のためのDjango入門

■第15話:NumPyの便利な機能

(最終更新日:2023.06.11)

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

「NumPy配列を自由自在に操ろう!」

これまで、行列計算から統計計算、DeepLearningまで、幅広い領域でNumPyが便利に使えることを説明してきた。 今回は、今まで紹介してこなかったNumPyの便利機能について紹介したいと思う。

配列の結合と分離、条件付き演算というフィルタリング的な機能まで、NumPyは様々な操作に対応する。 ぜひ、今からでも使えるようになろう。


1.配列の結合と分割

NumPyには、配列を結合する関数と分割する関数が容易されている。 np.concatenateは結合する関数で、使い方は以下の通りになる。 2つの配列が結合されて、[1, 2, 3, 4, 5, 6]になる。

NumPy配列の結合

NumPy配列の結合、np.concatenate

また、分割する関数はnp.splitで、使い方は以下の通りになる。 元の配列が3分割されて[1,2],[3,4],[5,6]になる。

NumPy配列の分割

NumPy配列の分割、np.split

2.条件付き演算

NumPyには条件付き演算を行う関数が用意されている。 それがnp.whereで、NumPy配列内の要素を選択するための便利な関数である。 下記では、4を超える値を選択しており、フィルタされて配列[5, 6]になっている。

NumPy配列の選択関数

NumPy配列の選択関数、where

以上のように、NumPyはPythonの科学計算とデータ分析のエコシステムにおいて、中心的な役割を果たしている。 これらのライブラリは互いに深く関連しており、一緒に使用されることで、強力なデータ分析ツールセットを形成している。 同様の操作が第13話で紹介したmaskingでも可能である。 実際は中の挙動が異なるのだが、どちらもある条件を満たす要素を抽出すると考えて良いだろう。


3.ファンシーインデックス

ファンシーインデックス(または整数配列インデックス)は、NumPy配列に対して特定の順序でインデックスを指定するための機能である。 これにより、複雑な配列構造を生成したり、配列の部分集合を特定の順序で抽出したりすることができる。 以下にその使用例を示す。NumPy配列とインデックス配列をそれぞれ作成し、ファンシーインデックスという手法で、 インデックス配列で指定した要素のみを取り出している。下記では1,3,4番目の要素を抽出し、[20, 40, 50]が取得された。

ファイシーインデックスによる抽出

ファイシーインデックスによる配列の抽出

この操作が凄いのは、多次元配列にも適用できるところである。 取得したい行要素と列要素をそれぞれNumPy配列で指定することで、多次元配列から選択的に要素を抽出できる。 下記では、1行2列目の要素と2行2列目の要素を抽出(0行、0列から数えるものとする)している。結果、[5, 9]が抽出された。

ファイシーインデックスによる多次元配列の抽出

ファイシーインデックスによる多次元配列の抽出

4.ユニバーサル関数

ユニバーサル関数はNumPyが提供する機能の一つで、配列の要素ごとに操作を行う関数のことを指す。 これにより、ループを書くことなく、配列の全要素に対する操作を効率的かつ簡潔に書くことができる。 これは、Pythonの組込関数(例えば、add、subtract、multiplyなど)が一度に一つの要素しか処理できないのと対照的である。

NumPyのユニバーサル関数は、C言語レベルで実装されているため、 Pythonの組み込み関数よりも大幅に高速だ。 これは「ベクトル化」と呼ばれる手法の一種で、コードの可読性とパフォーマンスの両方を向上させることができる。 以下に、ユニバーサル関数の基本的な使い方を示す。 各要素を2乗するsquare、各要素に値を加えるadd、各要素を逆数にするreciprocal等がある。 reciprocalは値が小数になるので、型をfloatにしている。一気に計算できているのが分かるだろう。

NumPyのユニバーサル関数

NumPyのユニバーサル関数

5.まとめ

今回、NumPyで今まで説明してこなかった便利な関数についてまとめてみた。 NumPyは値がベクトル化されていて、一気に高速に計算処理できるというのが、圧倒的な強みである。 しかも、コードの可読性に優れ、比較的簡単なコードで計算できるのも大きい。 少なくとも、今回説明したユニバーサル関数と13話で説明したブロードキャスティングだけは使えるようになろう。

全5回に続いたNumPyシリーズも今回で終了だが、勉強だけにとどまらずぜひ、実務でも活用してみよう。 きっと、様々な場面で役に立つはずだ。


▼参考図書、サイト

NumPyで条件に応じた処理を行うnp.whereの使い方  note.nkmk.me
NumPyのファンシーインデックス(リストによる選択と代入)  note.nkmk.me
NumPy入門 代表的なユニバーサル関数  PythonエンジニアによるPython3学習サイト


Introduction to Django for Beginners ■ Episode 15: Useful Features of NumPy (Last updated: 2023.06.11) Image of the Django framework You can read this article in 6 minutes! (If the images are small, try rotating your phone horizontally) "Master NumPy arrays freely!" Until now, we have discussed how NumPy is useful in various areas such as matrix calculations, statistics, and deep learning. In this article, we’ll cover some of the convenient NumPy features that haven't been introduced yet. From combining and splitting arrays to conditional operations like filtering, NumPy supports a wide range of operations. Let’s start using them right away. [Table of Contents] Combining and Splitting Arrays Conditional Operations Fancy Indexing Universal Functions Summary 1. Combining and Splitting Arrays NumPy provides functions to concatenate and split arrays. The `np.concatenate` function is used to combine arrays, as shown below. Two arrays are combined to form [1, 2, 3, 4, 5, 6]. Concatenating NumPy arrays Combining NumPy arrays with np.concatenate To split arrays, use `np.split`. In the following example, the original array is split into three parts: [1,2], [3,4], and [5,6]. Splitting NumPy arrays Splitting NumPy arrays with np.split 2. Conditional Operations NumPy offers the `np.where` function for conditional operations. It is a convenient tool to select elements in an array based on a condition. In the example below, values greater than 4 are selected, resulting in the array [5, 6]. Selecting NumPy array elements Element selection using np.where As shown above, NumPy plays a central role in Python's ecosystem for scientific computing and data analysis. These libraries are closely integrated, forming a powerful data analysis toolkit when used together. Similar operations can be achieved using masking, introduced in Episode 13. While the internal mechanics differ, both allow you to extract elements based on a condition. 3. Fancy Indexing Fancy indexing (or integer array indexing) allows you to specify indices in a particular order when accessing elements in a NumPy array. This enables you to extract subsets or create complex array structures. In the example below, a NumPy array and an index array are created. Using fancy indexing, the elements at positions 1, 3, and 4 are extracted, resulting in [20, 40, 50]. Fancy indexing element extraction Extracting elements using fancy indexing This technique is powerful because it also works on multidimensional arrays. By specifying the rows and columns you want using arrays, you can selectively extract elements from 2D arrays. In the example below, the elements at row 1, column 2 and row 2, column 2 are extracted (indexing starts from 0), resulting in [5, 9]. Fancy indexing on multidimensional arrays Fancy indexing on multidimensional arrays 4. Universal Functions Universal functions (ufuncs) are NumPy functions that perform element-wise operations on arrays. This allows you to efficiently perform operations on all elements without writing loops. This is in contrast to Python's built-in functions, which typically operate on one element at a time. NumPy’s ufuncs are implemented in C, making them significantly faster than equivalent Python code. This technique is known as “vectorization,” which improves both performance and code readability. Below are examples of basic ufuncs: `square` (squares each element), `add` (adds values), and `reciprocal` (returns the reciprocal). Since `reciprocal` results in floating-point values, the array is cast to float. Notice how all operations are performed at once. NumPy universal functions Universal functions in NumPy 5. Summary In this article, we covered some useful NumPy functions that hadn’t been introduced before. One of NumPy's greatest strengths is its ability to perform fast, vectorized operations. Moreover, the code is easy to read and relatively simple to write. At the very least, make sure you understand how to use universal functions and broadcasting (covered in Episode 13). This is the final episode in our five-part NumPy series. Don’t just study—apply what you've learned in real-world projects! NumPy will definitely be helpful in many situations. ▼ References   How to Use np.where for Conditional Processing in NumPy — note.nkmk.me   NumPy Fancy Indexing (Selection and Assignment by List) — note.nkmk.me   Introduction to NumPy: Popular Universal Functions — Python3 Learning Site by Python Engineer