並べ替えと検索

1. 学習内容



2. 主要な概念

(1) 並べ替え

PYTHON
import numpy as np

a = np.array([3, 1, 4, 1, 5, 9, 2, 6])

print(np.sort(a))       # [1 1 2 3 4 5 6 9]
print(np.argsort(a))    # [1 3 0 6 2 4 7 5]  (indices)

# 2D sorting
b = np.array([[3, 1, 4],
              [1, 5, 9]])
print(np.sort(b, axis=0))  # sort each column
print(np.sort(b, axis=1))  # sort each row
TEXT
> Output: Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.

(2) 検索

PYTHON
import numpy as np

a = np.array([1, 3, 5, 7, 9])

# Find insertion positions (array must be sorted)
print(np.searchsorted(a, 4))  # 2 (insert between 3 and 5)
print(np.searchsorted(a, [2, 6, 8]))  # [1 3 4]

# Find indices where condition is True
print(np.where(a > 4))  # (array([2, 3, 4]),)
TEXT
> Output: Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.

(3) ユニーク

PYTHON
a = np.array([3, 1, 4, 1, 5, 9, 2, 6, 5, 3])

print(np.unique(a))  # [1 2 3 4 5 6 9]

# With counts
vals, counts = np.unique(a, return_counts=True)
print(vals)     # [1 2 3 4 5 6 9]
print(counts)   # [2 1 2 1 2 1 1]
TEXT
> Output: Run NumPy 2.x in your local Python environment to see the ndarray output. The Piston server does not have NumPy pre-installed — install it locally (`pip install numpy`) and compare. Actual values may vary by NumPy version and random seed.

(1) ▶ サンプル:配列のソート(難易度 ⭐)

PYTHON
import numpy as np

a = np.array([3, 1, 4, 1, 5, 9, 2, 6])

# Sort returns a sorted copy
sorted_a = np.sort(a)
print("Original:", a)
print("Sorted:", sorted_a)

# In-place sort
a.sort()
print("In-place:", a)

# 2D sort along axis
b = np.array([[3, 1, 4], [1, 5, 9]])
print("Sort columns:\n", np.sort(b, axis=0))
print("Sort rows:\n", np.sort(b, axis=1))

出力:

TEXT
原文:[3 1 4 1 5 9 2 6]
並べ替え済み:[1 1 2 3 4 5 6 9]
インプレース:[1 1 2 3 4 5 6 9]
列の並べ替え:
 [[1 1 4]
 [3 5 9]]
行の並べ替え:
 [[1 3 4]
 [1 5 9]]

(2) ▶ サンプル:argsort の使用(難易度 ⭐⭐)

PYTHON
import numpy as np

scores = np.array([85, 92, 78, 95, 88])
names = np.array(['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'])

# Get indices that would sort scores
idx = np.argsort(scores)
print("Indices:", idx)
print("Sorted scores:", scores[idx])

# Sort names by their scores (descending)
desc_idx = np.argsort(-scores)
print("Ranking:")
for rank, i in enumerate(desc_idx, 1):
    print(f"  {rank}. {names[i]}: {scores[i]}")

出力:

TEXT
インデックス:[2 0 4 1 3]
スコア順:[78 85 88 92 95]
ランキング:
  1. ダイアナ:95
  2. ボブ:92
  3. イヴ:88
  4. アリス:85
  5. チャーリー:78

(3) ▶ サンプル:個数とともに一意の値を抽出する(難易度 ⭐)

PYTHON
import numpy as np

grades = np.array(['A', 'B', 'A', 'C', 'B', 'A', 'B', 'B', 'C', 'A'])

unique, counts = np.unique(grades, return_counts=True)
print("Grades:", unique)
print("Counts:", counts)

# Find where to insert values into a sorted array
sorted_arr = np.array([1, 3, 5, 7, 9])
pos = np.searchsorted(sorted_arr, [2, 4, 6, 8])
print("Insertion positions:", pos)

出力:

TEXT
成績:['A' 'B' 'C']
カウント:[4 4 2]
挿入位置:[1 2 3 4]

Q np.sort は元の配列を変更しますか?
A いいえ。ソート済みのコピーを返します。コピーを作成せずに元の配列をソートするには、a.sort()(インプレース方式)を使用してください。
Q np.sortnp.argsort の違いは何ですか?
A np.sort はソート済みの値を返します。 np.argsortは、ソートされた配列を生成するためのインデックスを返します。複数の配列を同じ順序でソートする必要がある場合は、argsortを使用してください。
Q np.partition とは何ですか?
A 配列を部分的にソートし、k番目に小さい要素が最終的な位置に配置され、その前に小さい要素、後に大きい要素が(任意の順序で)並ぶようにするアルゴリズムです。トップkクエリに対しては、完全ソートよりも高速です。

❓ よくある質問

Q 最も重要なポイントは何か?
A NumPyの演算はベクトル化されているため、パフォーマンスを向上させるにはPythonのループは避けるべきだ。
Q さらに詳しく知りたい場合はどうすればよいですか?
A 詳細なリファレンスや高度なトピックについては、numpy.org の NumPy 公式ドキュメントをご覧ください。
Q これはNumPy 2.xでも動作しますか?
A はい。すべての例はNumPy 2.xと互換性があります。一部の古いAPI(np.random.seedなど)は引き続きサポートされていますが、最新の代替APIの使用をお勧めします。

📖 まとめ



📝 練習問題

  1. 初心者向け(難易度 ⭐):0~99の範囲のランダムな整数20個からなる配列を作成してください。その配列をソートし、ソート後のインデックスを求め、重複のない値を見つけ出してください。

  2. 中級(難易度 ⭐⭐):2つの配列「names」と「scores」を作成します。「scores」に対して np.argsort を使用し、両方の配列を並べ替えて、得点が最も高い名前が先頭に来るようにしてください。

  3. 上級 (難易度 ⭐⭐⭐): np.searchsorted を使用して、np.sort を呼び出さずに、2つのソート済み配列を1つのソート済み配列に結合してください。結果が正しくソートされていることを確認してください。

Web-Tutorial.com

Web-Tutorial 技術チーム

複数の開発者によって共同維持されているプログラミングチュートリアルプラットフォーム。各チュートリアルは専門分野の開発者が執筆・レビューしています。正確で信頼性の高いコンテンツを目指しています — 問題を見つけた場合はお知らせください。

100%