2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

NumPyの基本&応用

Last updated at Posted at 2025-02-05

NumPyとは?

NumPy(Numerical Python)は、Pythonで数値計算を高速に処理するためのライブラリ。
大量のデータを効率的に扱え、データ分析や機械学習で必須!

1. NumPy配列の作成

🔹 PythonのリストをNumPy配列(ndarray)に変換
🔹 計算が高速&多次元配列が扱える

python
import numpy as np

# PythonリストからNumPy配列を作成
arr = np.array([1, 2, 3, 4, 5])
print(arr)  # 出力: [1 2 3 4 5]
print(type(arr))  # 出力: <class 'numpy.ndarray'>

# 2次元配列(行列)
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix)

2. 特殊な配列の作成

🔹 すべて0 or 1 の配列を簡単に作れる
🔹 ランダムな値の配列も生成可能

python
# すべて0の配列(3×3)
zeros = np.zeros((3,3))
print(zeros)

# すべて1の配列(2×4)
ones = np.ones((2,4))
print(ones)

# ランダムな数値(0〜1の間, 4×4)
random_arr = np.random.rand(4,4)
print(random_arr)

# 整数のランダムな配列(0〜10の間, 3×3)
rand_ints = np.random.randint(0, 10, (3,3))
print(rand_ints)

3. 配列の演算

🔹 配列の足し算・引き算・掛け算などを要素ごとに実行

python

a = np.array([10, 20, 30])
b = np.array([1, 2, 3])

print(a + b)  # [11 22 33] (各要素ごとに加算)
print(a - b)  # [9 18 27] (各要素ごとに減算)
print(a * b)  # [10 40 90] (各要素ごとに乗算)
print(a / b)  # [10. 10. 10.] (各要素ごとに除算)
print(a ** 2) # [100 400 900] (各要素の2乗)

4. 配列の形状操作(リシェイプ)

🔹 配列の形を変更(reshape)し、2D・3Dに変換可能

python
arr = np.arange(1, 10)  # 1〜9の配列
print(arr)

# 1D → 2D(3行3列)
reshaped = arr.reshape(3,3)
print(reshaped)

5. 統計計算

🔹 平均値・中央値・標準偏差などの統計処理が簡単に

python

data = np.array([10, 20, 30, 40, 50])

print(np.mean(data))   # 平均: 30.0
print(np.median(data)) # 中央値: 30.0
print(np.std(data))    # 標準偏差
print(np.max(data))    # 最大値
print(np.min(data))    # 最小値

6. 条件に合うデータの抽出

🔹 条件を指定してデータをフィルタリング

python
numbers = np.array([5, 10, 15, 20, 25, 30])

# 15以上の要素を抽出
filtered = numbers[numbers >= 15]
print(filtered)  # 出力: [15 20 25 30]

7. ブロードキャスト(異なる形の配列の計算)

🔹 異なる形の配列同士の演算ができる

python
matrix = np.array([[1, 2, 3], [4, 5, 6]])
vector = np.array([10, 20, 30])

# 各行に [10, 20, 30] を加算
result = matrix + vector
print(result)

まとめ

NumPyはPythonで高速な数値計算ができるライブラリ

・1D, 2D, 多次元の配列を簡単に作成&操作
・特殊な配列(ゼロ, ワン, ランダム)を簡単に生成
・高速な数値演算(+,-,*,/,** など)に対応
・統計計算(平均,中央値,標準偏差,最大・最小 など)が一発でできる
・条件に合うデータをフィルタリング可能
・異なる形の配列同士の計算(ブロードキャスト)ができる

NumPyの活用シーン

✅ データ分析・統計処理を高速化したい
✅ 大量の数値データを処理したい
✅ 機械学習・AIの前処理に使いたい
✅ 行列演算を手軽に実行したい

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?