PythonとNumPy:基礎から実践まで練習問題10選
Pythonは汎用性の高いプログラミング言語であり、データ分析、機械学習、科学計算などの分野で広く利用されています。特に数値計算においては、NumPyライブラリが不可欠なツールとなります。NumPyは、多次元配列オブジェクト(ndarray)を提供し、ベクトル化された演算を効率的に実行できるため、Pythonだけで数値計算を行うよりも大幅に高速化できます。
本記事では、NumPyの基礎から応用までをカバーする練習問題10選を紹介します。各問題には解説とサンプルコードが含まれており、NumPyの理解を深め、実践的なスキルを習得するのに役立ちます。
1. NumPy配列の作成
問題: 0から9までの整数を持つ1次元NumPy配列を作成し、その形状とデータ型を表示してください。
解説: NumPy配列はnumpy.array()
関数を使用して作成できます。引数にはPythonのリストやタプルなどを渡します。配列の形状はshape
属性で、データ型はdtype
属性で確認できます。NumPy配列は、Pythonのリストよりも効率的に数値データを格納し、高速な数値演算を可能にします。dtype
は、配列内の要素がどのようなデータ型(整数、浮動小数点数など)を持つかを指定します。デフォルトでは、NumPyはデータの型を自動的に推測しますが、明示的に指定することもできます。
サンプルコード:
import numpy as np # 0から9までの整数を持つ1次元NumPy配列を作成 arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) # 配列の形状を表示 print("形状:", arr.shape) # 出力: (10,) # 配列のデータ型を表示 print("データ型:", arr.dtype) # 出力: int64 (環境によって異なる)
参照: NumPy配列の作成
(English Explanation): NumPy arrays are created using the numpy.array()
function. You can pass a Python list or tuple as an argument. The shape of the array is accessed through the shape
attribute, and the data type through the dtype
attribute. NumPy arrays offer more efficient storage and faster numerical operations compared to standard Python lists. The dtype
specifies the data type (integer, float, etc.) of the elements within the array. NumPy often infers the data type automatically, but you can also specify it explicitly.
2. 配列の形状変更
問題: 1次元NumPy配列 arr
を、3行4列の2次元配列にreshapeしてください。
解説: reshape()
メソッドを使用すると、配列の形状を変更できます。新しい形状は、元の配列の要素数を満たす必要があります。例えば、1次元配列を2次元配列に変換する場合、新しい形状の要素数の積が元の配列の要素数と一致している必要があります。reshape()
メソッドは、データのコピーを作成せずに、配列のデータを再配置します。
サンプルコード:
import numpy as np # 1次元NumPy配列を作成 arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) # 形状を変更 (3行4列) reshaped_arr = arr.reshape(3, 4) # 結果を表示 print(reshaped_arr)
参照: NumPy配列の形状変更
(English Explanation): The reshape()
method allows you to change the shape of an array. The new shape must have the same number of elements as the original array. For example, when reshaping a 1D array into a 2D array, the product of the dimensions in the new shape must equal the total number of elements in the original array. The reshape()
method rearranges the data without creating a copy.
3. 配列のスライスとインデックス指定
問題: 2次元NumPy配列 arr
の、1行目から3行目まで(3行目を含む)と、すべての列を選択し、新しい配列として抽出してください。
解説: NumPy配列はPythonのリストと同様にスライスを使用して要素にアクセスできます。2次元配列では、[行インデックス, 列インデックス]
の形式で指定します。スライスを使用すると、配列の一部を効率的に抽出できます。NumPyのスライスは、元の配列と共有メモリを持つビュー(view)を返すため、新しい配列を作成するオーバーヘッドがありません。
サンプルコード:
import numpy as np # 2次元NumPy配列を作成 arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) # 1行目から3行目まで(3行目を含む)と、すべての列を選択 sliced_arr = arr[0:3, :] # または arr[:3, :] # 結果を表示 print(sliced_arr)
参照: NumPy配列のスライス
(English Explanation): NumPy arrays can be accessed using slicing, similar to Python lists. For 2D arrays, you specify elements using [row index, column index]
. Slicing allows efficient extraction of portions of the array. NumPy slices return a view (a reference to the original data) rather than creating a new copy, which avoids overhead.
4. 配列の要素へのアクセス
問題: 2次元NumPy配列 arr
の、2行3列目の要素の値を取得し、表示してください。
解説: 配列の要素には、インデックスを使用して直接アクセスできます。2次元配列では、[行インデックス, 列インデックス]
の形式で指定します。インデックスは0から始まることに注意してください。NumPy配列の要素へのアクセスは、Pythonリストよりも高速です。
サンプルコード:
import numpy as np # 2次元NumPy配列を作成 arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # 2行3列目の要素の値を取得 element = arr[1, 2] # または arr[1][2] # 結果を表示 print(element) # 出力: 6
5. 配列のブールインデックス
問題: NumPy配列 arr
の、3より大きい要素のみを選択し、新しい配列として抽出してください。
解説: ブールインデックスを使用すると、条件を満たす要素だけを抽出できます。条件式の結果がTrueとなる要素に対応する値が選択されます。ブールインデックスは、データ分析において特定の条件に合致するデータを効率的に抽出するために非常に役立ちます。
サンプルコード:
import numpy as np # NumPy配列を作成 arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) # 3より大きい要素のみを選択 filtered_arr = arr[arr > 3] # 結果を表示 print(filtered_arr) # 出力: [4 5 6 7 8 9]
6. 配列の算術演算
問題: NumPy配列 arr1
と arr2
に対して、要素ごとの加算、減算、乗算、除算を実行し、それぞれの結果を表示してください。
解説: NumPyはベクトル化された演算をサポートしており、配列全体に対して算術演算を効率的に実行できます。これは、Pythonのループを使用するよりも大幅に高速です。NumPyのベクトル化された演算は、C言語で実装されているため、非常に効率的です。
サンプルコード:
import numpy as np # NumPy配列を作成 arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) # 要素ごとの加算 addition_result = arr1 + arr2 print("加算:", addition_result) # 出力: [5 7 9] # 要素ごとの減算 subtraction_result = arr1 - arr2 print("減算:", subtraction_result) # 出力: [-3 -3 -3] # 要素ごとの乗算 multiplication_result = arr1 * arr2 print("乗算:", multiplication_result) # 出力: [ 4 10 18] # 要素ごとの除算 division_result = arr1 / arr2 print("除算:", division_result) # 出力: [0.25 0.4 0.5 ]
7. NumPy関数の利用
問題: NumPy配列 arr
の、すべての要素の合計、平均、最大値、最小値を計算し、それぞれ表示してください。
解説: NumPyは、数学関数や統計関数など、さまざまな便利な関数を提供しています。これらの関数を使用すると、配列に対して複雑な演算を簡単に行うことができます。NumPyの関数は、ベクトル化されているため、高速に実行されます。
サンプルコード:
import numpy as np # NumPy配列を作成 arr = np.array([1, 2, 3, 4, 5]) # 要素の合計 sum_result = np.sum(arr) print("合計:", sum_result) # 出力: 15 # 要素の平均 mean_result = np.mean(arr) print("平均:", mean_result) # 出力: 3.0 # 最大値 max_result = np.max(arr) print("最大値:", max_result) # 出力: 5 # 最小値 min_result = np.min(arr) print("最小値:", min_result) # 出力: 1
参照: NumPy関数
(English Explanation): NumPy provides a wide range of mathematical and statistical functions that simplify complex operations on arrays. These functions are vectorized, meaning they operate efficiently on entire arrays without the need for explicit loops. This significantly speeds up calculations compared to using Python's built-in looping mechanisms.
8. 行列の積
問題: 2つの行列 matrix1
と matrix2
の行列積を計算し、結果を表示してください。
解説: NumPyは、行列積を効率的に計算するための機能を提供しています。numpy.dot()
関数または @
演算子を使用できます。行列積は、線形代数において重要な演算であり、機械学習やデータ分析などの分野で広く利用されています。
サンプルコード:
import numpy as np # 行列を作成 matrix1 = np.array([[1, 2], [3, 4]]) matrix2 = np.array([[5, 6], [7, 8]]) # 行列積を計算 (numpy.dot()を使用) product_result = np.dot(matrix1, matrix2) print("行列積 (numpy.dot()):", product_result) # 行列積を計算 (@演算子を使用) product_result_at = matrix1 @ matrix2 print("行列積 (@演算子):", product_result_at)
参照: NumPy行列積
(English Explanation): NumPy provides efficient functions for calculating matrix products, essential in linear algebra and widely used in machine learning and data analysis. You can use either numpy.dot()
or the @
operator to compute the dot product of two matrices.
9. 配列の連結と分割
問題: 2つの1次元NumPy配列 arr1
と arr2
を連結し、新しい配列として作成してください。また、3つの1次元NumPy配列 arr1
, arr2
, arr3
をそれぞれ3等分に分割してください。
解説: NumPyは、配列の連結と分割のための関数を提供しています。numpy.concatenate()
関数を使用して配列を連結し、numpy.split()
関数を使用して配列を分割できます。これらの操作は、データの前処理や後処理において頻繁に使用されます。
サンプルコード:
import numpy as np # 1次元NumPy配列を作成 arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) arr3 = np.array([7, 8, 9]) # 配列の連結 concatenated_arr = np.concatenate((arr1, arr2)) print("連結:", concatenated_arr) # 出力: [1 2 3 4 5 6] # 配列の分割 split_arr = np.split(np.array([10, 20, 30, 40, 50, 60]), 3) print("分割:", split_arr) # 出力: [array([10, 20]), array([30, 40]), array([50, 60])]
参照: NumPy配列の連結 NumPy配列の分割
(English Explanation): NumPy provides functions for concatenating and splitting arrays, common operations in data preprocessing and post-processing. numpy.concatenate()
joins arrays together, while numpy.split()
divides an array into multiple sub-arrays.
10. ブロードキャスト
問題: NumPy配列 arr
とスカラー値 scalar
を加算し、結果を表示してください。
解説: ブロードキャストは、形状の異なる配列同士を演算できるようにするNumPyの機能です。スカラー値を配列にブロードキャストすることで、要素ごとの加算を実行できます。これにより、コードの簡潔性と効率性を向上させることができます。
サンプルコード:
import numpy as np # NumPy配列を作成 arr = np.array([1, 2, 3]) # スカラー値 scalar = 5 # 配列とスカラーを加算 (ブロードキャスト) broadcasted_result = arr + scalar # 結果を表示 print(broadcasted_result) # 出力: [6 7 8]
参照: NumPyブロードキャスト
(English Explanation): Broadcasting is a powerful feature in NumPy that allows operations between arrays with different shapes. It automatically expands the dimensions of smaller arrays to match those of larger arrays, enabling element-wise operations without explicit looping or reshaping. This simplifies code and improves efficiency.