Web制作、Web開発の歩き方

初心者のためのDjango入門

■第11話:NumPyの使い方と基本的概念

(最終更新日:2023.06.03)

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

「Python使うならNumPyを使おう!」

DjangoはPython製のフレームワークである。よって、Pythonの強力なライブラリと共に用いることで、より強力なツールとなる。 今回は、その強力なライブラリの1つとして、NumPyを取り上げる。

NumPyは主に数値データの配列や行列を扱うのに適しており、高速な数値演算や統計的分析機能が特徴だ。 さらに、多次元配列を扱うことが得意なため、データサイエンスや機械学習、画像処理、科学技術計算などの分野で広く利用されている。 Web上でも、画像処理や統計的な計算は様々な応用ができることは容易に想像がつくだろう。

仮想環境の有効化

Pythonによる統計分析のイメージ

今回から数回に分けて、Pythonの最も有用なライブラリの1つであるNumPyの使い方や有用性を説明したいと思う。


1.NumPyの重要性:なぜPythonプログラマーはこれを知るべきか?

Pythonはその自由度と可読性の高さから多くの分野で利用されている。 しかし、実行速度の遅さから大量の数値データを処理するには適していない。 しかし、ここでNumPyが活躍する。NumPyはC言語やFORTRANで書かれているため、大量の数値データを非常に効率的に処理することができる。 また、NumPyは数値計算だけでなく、データの整形やデータ抽出など、データ処理の総合的なサポートをする。

C言語

C言語のイメージ

さらに、NumPyは他の多くのデータ分析ライブラリ(Pandas、Scipy、Matplotlibなど)の基盤となっており、 これらのライブラリとの互換性を保つことで、Pythonエコシステムの中で一貫したデータ操作と効率的な分析体験をすることができる。

今回から、NumPyについての基本的な使用法から高度な機能まで、具体的な例を通じて学んでいこう。

2.NumPyのインストール

まずは、NumPyをインストールする前にPythonをインストールするところから始めよう。 PythonはWindows、Mac、Linuxとあらゆるオペレーティングシステムでインストール可能です。 公式サイトから、まずはダウンロードしてインストールしよう。

Pythonのインストールが無事終了したら、直接ライブラリをインストールせずに、仮想環境を構築する。 仮想環境を用いるのは、プロジェクトごとにインストールするライブラリのバージョンを揃え、安定稼働させるだめだ。 Pythonにはvenvというモジュールが組み込まれており、これを用いて仮想環境を作成することができる。 venvを使うには、例えば「python3 -m venv myenv」とターミナル(Windowsならコマンドプロンプト)で入力しよう。 python3の3は必要ない場合もある。 (WindowsでデフォルトでインストールしているPythonだとvenvが上手く動かなかったりする。その場合は公式サイトのPythonをインストールしよう。) また、myenvの部分は、仮想環境の名前なので、覚えやすい名前をつけよう。 これで、「myenv」という名前の仮想環境が作成される。これを有効にするには以下のコマンドを入力する。 下記の1行目がWindowsのコマンドで、2行目がLinux、Macのコマンドになる。 これで、仮想環境に入ることができた。

仮想環境の有効化

仮想環境の有効化

次に、この仮想環境にNumPyをインストールする。NumPyをインストールするのはとても簡単だ。 下記とおりpipでインストールできる。

NumPyのインストールコマンド

NumPyのインストールコマンド

インストールしたら、実際のPythonのコードで利用する場合は「import numpy as np」を最初に書こう。 これで、Pythonのコード上でnumpyを使うことができる。環境構築はこのように行う。

3.NumPyの基本的な概念

NumPyを使い始める前に理解しておくべき基本的な概念は主に以下の3つである。 配列(Array)、行列(Matrix)、ベクトル(Vector)だ。 これらは全てNumpyの中心的なデータ構造であるNumpy配列に関連している。

NumPy配列は、同じ種類のデータ(主に数値)を格納する多次元の線形式だ。 NumPy配列は、Pythonのリストと似ているが、計算速度やメモリ効率において優れている。 NumPy配列は0次元(スカラー)、1次元(ベクトル)、2次元(行列)、またはそれ以上の次元を持つことができる。

様々なNumPy配列

様々なNumPy配列

行列は、2次元のNumpy配列で、数学的な操作(例えば、行列の乗算、逆行列、行列のランクなど)に利用される。 行列は、行と列の両方を持つデータ構造で、2次元のデータを格納するのに適している。

ベクトルは、1次元のNumpy配列で、スカラーよりも複雑な計算に利用される。 ベクトルは数学的な操作(例えば、ベクトルの加算、スカラーとの乗算、ドット積など)に利用される。 これらの概念を理解することで、Numpyを用いたデータ操作と計算がより容易になる。 次のセクションでは、これらの概念を具体的にどのように使用するかについて見ていこう。


4.まとめ

今回、Pythonのインストールからvenvによる仮想環境の構築、NumPyのインストールについて説明した。 加えて、NumPyの基本的な概念、データ構造である、配列、行列、ベクトルについて説明した。 実際に使うのはこれからだが、まずは自分のPCでNumPyを使えるようにしよう。


▼参考図書、サイト

Windowsでvenvで仮想環境を作成して立ち上げるまでやる  Zenn
NumPy 配列の基礎  Machine Learning Meets Python


Django Tutorial for Beginners ■Episode 11: How to Use NumPy and Its Basic Concepts (Last updated: 2023.06.03) Image of Django framework This article takes about 5 minutes to read! (Rotate your phone sideways if the image appears small) "If you're using Python, use NumPy!" Django is a framework written in Python. Therefore, using it with Python’s powerful libraries makes it an even stronger tool. This time, we’ll focus on one such powerful library — NumPy. NumPy is particularly suited for handling numerical data in arrays and matrices, and is known for its fast numerical operations and statistical analysis features. Because it excels in handling multi-dimensional arrays, it is widely used in data science, machine learning, image processing, and scientific computing. On the web, it’s easy to imagine how image processing and statistical calculations can have many applications. Statistical analysis with Python Image of statistical analysis using Python Over the next few articles, we’ll explore how to use NumPy and why it’s so useful, starting with the basics. [Table of Contents] Why NumPy Is Essential for Python Programmers Installing NumPy Basic Concepts of NumPy Summary 1. Why NumPy Is Essential for Python Programmers Python is widely used due to its flexibility and readability. However, its execution speed is relatively slow, which makes it less ideal for processing large amounts of numerical data. This is where NumPy comes in. Written in C and FORTRAN, NumPy can efficiently process large-scale numerical data. Beyond calculations, it also supports data reshaping and extraction — making it a comprehensive tool for data processing. C language Image representing the C programming language Moreover, NumPy serves as the foundation for many other data analysis libraries such as Pandas, SciPy, and Matplotlib. Its compatibility with these tools provides a consistent and efficient data handling experience across the Python ecosystem. Starting now, let’s dive into NumPy from the basics to advanced features with concrete examples. 2. Installing NumPy Before installing NumPy, let’s start by installing Python itself. Python can be installed on Windows, macOS, and Linux. Download it from the official website and install it. Once Python is installed, we recommend setting up a virtual environment rather than installing libraries globally. Virtual environments help isolate project dependencies and ensure consistent environments. Python includes a built-in module called `venv` for this purpose. You can create a virtual environment by typing `python3 -m venv myenv` in the terminal (or Command Prompt on Windows). The `3` in `python3` may not be necessary depending on your system. (If the built-in Python on Windows doesn't work well with `venv`, try installing Python from the official website.) You can name the environment whatever you like — here we use `myenv`. To activate the virtual environment, use the following commands: The first line is for Windows, and the second is for Linux/macOS. Activate virtual environment Activating the virtual environment Next, install NumPy in the virtual environment using pip. It’s a simple one-line command as shown below. Command to install NumPy Command to install NumPy Once installed, include `import numpy as np` at the top of your Python script to use NumPy. That’s how to set up the environment for NumPy. 3. Basic Concepts of NumPy Before using NumPy, there are three basic concepts you should understand: arrays, matrices, and vectors. These are all related to the core data structure in NumPy — the NumPy array. A NumPy array is a multidimensional, linear structure that stores data of the same type (mostly numerical). It is similar to Python lists but is superior in terms of speed and memory efficiency. NumPy arrays can be 0-dimensional (scalar), 1D (vector), 2D (matrix), or even higher dimensions. Various NumPy arrays Various types of NumPy arrays A matrix is a 2D NumPy array used for mathematical operations like multiplication, inversion, or computing the rank. It has rows and columns, making it suitable for storing 2D data. A vector is a 1D NumPy array used for mathematical operations such as addition, scalar multiplication, or dot product. Understanding these core concepts will help you work with data and perform calculations more easily using NumPy. In the next section, we’ll look at how to use these concepts in practice. 4. Summary In this article, we covered how to install Python, create a virtual environment using venv, and install NumPy. We also explained the basic concepts and data structures in NumPy — arrays, matrices, and vectors. We haven’t used them yet, but make sure you can run NumPy on your PC before moving forward. ▼References   Creating and Activating a Virtual Environment with venv on Windows - Zenn   Basics of NumPy Arrays - Machine Learning Meets Python