【repeat, tile】numpyで配列の要素を繰り返す方法を解説

Python

numpyで配列の要素を繰り返したい場合、np.repeatnp.tileの2つの関数を使用できます。本記事では、これらの関数の使い方と違いを具体的なコード例とともに解説します。

np.repeat

np.repeatは配列の各要素を指定した回数だけ繰り返す関数です。

構文

np.repeat(a, repeats, axis=None)

パラメータ

  • a: 繰り返す配列
  • repeats: 繰り返し回数(整数または整数の配列)
  • axis: 繰り返しを行う軸(デフォルトはNone)

基本的な使い方

1次元配列の各要素を2回ずつ繰り返す例です。

import numpy as np

arr = np.array([1, 2, 3])
result = np.repeat(arr, 2)
print(result)
# [1 1 2 2 3 3]

要素ごとに異なる回数で繰り返し

各要素を異なる回数で繰り返す例です。

import numpy as np

arr = np.array([1, 2, 3])
result = np.repeat(arr, [2, 3, 1])
print(result)
# [1 1 2 2 2 3]

2次元配列での使用

2次元配列に対してaxisパラメータを指定して繰り返しを行う例です。

import numpy as np

arr = np.array([[1, 2], [3, 4]])
# 行方向に繰り返し
result_axis0 = np.repeat(arr, 2, axis=0)
print(result_axis0)
# [[1 2]
#  [1 2]
#  [3 4]
#  [3 4]]

# 列方向に繰り返し
result_axis1 = np.repeat(arr, 2, axis=1)
print(result_axis1)
# [[1 1 2 2]
#  [3 3 4 4]]

np.tile

np.tileは配列全体を指定した回数だけタイル状に繰り返す関数です。

構文

np.tile(A, reps)

パラメータ

  • A: 繰り返す配列
  • reps: 繰り返し回数(整数またはタプル)

基本的な使い方

1次元配列全体を3回繰り返す例です。

import numpy as np

arr = np.array([1, 2, 3])
result = np.tile(arr, 3)
print(result)
# [1 2 3 1 2 3 1 2 3]

多次元での繰り返し

配列を多次元方向に繰り返す例です。

import numpy as np

arr = np.array([1, 2, 3])
# 2行3列に配置
result = np.tile(arr, (2, 3))
print(result)
# [[1 2 3 1 2 3 1 2 3]
#  [1 2 3 1 2 3 1 2 3]]

2次元配列での使用

2次元配列をタイル状に繰り返す例です。

import numpy as np

arr = np.array([[1, 2], [3, 4]])
result = np.tile(arr, (2, 2))
print(result)
# [[1 2 1 2]
#  [3 4 3 4]
#  [1 2 1 2]
#  [3 4 3 4]]

違いと使い分け

np.repeatnp.tileの主な違いは以下の通りです。

繰り返しの単位

  • np.repeat: 各要素を個別に繰り返す
  • np.tile: 配列全体をブロック単位で繰り返す

実際の動作の違いを比較する例です。

import numpy as np

arr = np.array([1, 2, 3])

# repeatの場合
repeat_result = np.repeat(arr, 2)
print("repeat:", repeat_result)
# repeat: [1 1 2 2 3 3]

# tileの場合
tile_result = np.tile(arr, 2)
print("tile:", tile_result)
# tile: [1 2 3 1 2 3]

使い分けの指針

  • 要素レベルの繰り返しが必要な場合はnp.repeatを使用
  • 配列全体のパターン繰り返しが必要な場合はnp.tileを使用

データ拡張での使用例です。

import numpy as np

# 元データ
data = np.array([10, 20, 30])

# 各データポイントを3回ずつ複製(データ拡張)
expanded_data = np.repeat(data, 3)
print("expanded_data:", expanded_data)
# expanded_data: [10 10 10 20 20 20 30 30 30]

# パターンを2回繰り返し(周期的なデータ生成)
pattern_data = np.tile(data, 2)
print("pattern_data:", pattern_data)
# pattern_data: [10 20 30 10 20 30]

まとめ

numpyで配列の要素を繰り返す方法として、np.repeatnp.tileの2つの関数があります。np.repeatは各要素を個別に繰り返し、np.tileは配列全体をブロック単位で繰り返します。データの性質や目的に応じて適切な関数を選択することで、効率的な配列操作が可能になります。

タイトルとURLをコピーしました