LoginSignup
1
1

前回の記事に続いて、今回はさらに実用的なNumPyの使い方を紹介します。
データ解析でよく使用される応用的な操作について詳しく説明します。

応用的なNumPyの操作

1. 配列の結合と分割

データを扱う際には、複数の配列を結合したり、一つの配列を分割したりすることがよくあります。

import numpy as np

# 配列の結合
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
combined = np.concatenate((a, b))
print(f"結合された配列: {combined}")  # 結合された配列: [1 2 3 4 5 6]

# 2次元配列の結合
c = np.array([[1, 2], [3, 4]])
d = np.array([[5, 6], [7, 8]])
combined_2d = np.vstack((c, d))
print(f"結合された2次元配列:\n{combined_2d}")
# 結合された2次元配列:
# [[1 2]
#  [3 4]
#  [5 6]
#  [7 8]]

# 配列の分割
split_array = np.split(combined, 3)
print(f"分割された配列: {split_array}")
# 分割された配列: [array([1, 2]), array([3, 4]), array([5, 6])]
2. 配列の変形

データの形状を変更することは、解析の準備段階で頻繁に行われます。

# 配列のリシェイプ
e = np.array([[1, 2, 3], [4, 5, 6]])
reshaped = e.reshape((3, 2))
print(f"リシェイプされた配列:\n{reshaped}")
# リシェイプされた配列:
# [[1 2]
#  [3 4]
#  [5 6]]

# フラット化
flattened = e.flatten()
print(f"フラット化された配列: {flattened}")
# フラット化された配列: [1 2 3 4 5 6]
3. ブロードキャスト

異なる形状の配列間での演算も可能です。

# サンプルデータ
f = np.array([1, 2, 3])
g = np.array([[0], [1], [2]])

# ブロードキャストによる演算
result = f + g
print(f"ブロードキャストによる演算結果:\n{result}")
# ブロードキャストによる演算結果:
# [[1 2 3]
#  [2 3 4]
#  [3 4 5]]
4. 条件による選択

データの中から条件に基づいて要素を選択することも、NumPyを使うと簡単です。

# サンプルデータ
h = np.array([1, 2, 3, 4, 5, 6])

# 条件による選択
selected = h[h > 3]
print(f"条件に合致した要素: {selected}")
# 条件に合致した要素: [4 5 6]
5. 高度なインデックス操作

NumPyは柔軟なインデックス操作をサポートしています。

# サンプルデータ
i = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# 特定の行や列を選択
row = i[1, :]
print(f"2行目の要素: {row}")
# 2行目の要素: [4 5 6]

column = i[:, 1]
print(f"2列目の要素: {column}")
# 2列目の要素: [2 5 8]

# 複数の行や列を選択
subarray = i[0:2, 1:3]
print(f"部分配列:\n{subarray}")
# 部分配列:
# [[2 3]
#  [5 6]]
6. ランダムサンプルの生成

ランダムなサンプルを生成することは、シミュレーションや統計解析でよく使用されます。

# ランダムな整数の配列を生成
random_integers = np.random.randint(0, 10, size=(3, 3))
print(f"ランダムな整数の配列:\n{random_integers}")
# ランダムな整数の配列:
# [[4 9 0]
#  [1 5 7]
#  [6 3 2]]

# ランダムな浮動小数点数の配列を生成
random_floats = np.random.random((3, 3))
print(f"ランダムな浮動小数点数の配列:\n{random_floats}")
# ランダムな浮動小数点数の配列:
# [[0.56792387 0.27218365 0.45603387]
#  [0.94244895 0.18355667 0.78373165]
#  [0.62866469 0.49440931 0.22756961]]

# 正規分布に従うランダムな数の配列を生成
random_normal = np.random.randn(3, 3)
print(f"正規分布に従うランダムな数の配列:\n{random_normal}")
# 正規分布に従うランダムな数の配列:
# [[ 0.75388898 -0.58065735 -0.45284685]
#  [-1.45413148 -0.12491374 -1.40538161]
#  [ 1.4576425  -0.19432105  1.12135873]]

以上


1
1
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
1
1