Warning: Undefined variable $position in /home/pystyles/pystyle.info/public_html/wp/wp-content/themes/lionblog/functions.php on line 4897

pandas – repeat で各要素を繰り返した Series を作成する

pandas – repeat で各要素を繰り返した Series を作成する

概要

Series.repeat で各要素を指定回数だけ繰り返した Series を作成する方法について解説します。

Advertisement

pandas.Series.repeat

pandas.Series.repeat() は、Series の各要素を指定回数だけ繰り返した Series を作成して返します。

Series.repeat(self, repeats, axis=None)
引数
名前 デフォルト値
repeats int or array of ints
繰り返す回数

返り値
名前 説明
Series Newly created Series with repeated elements.

int を指定した場合、すべての要素をその回数だけ繰り返します。

In [1]:
import pandas as pd

s = pd.Series([1, 2, 3])

print(s.repeat(2))
0    1
0    1
1    2
1    2
2    3
2    3
dtype: int64

各要素ごとに繰り返す回数を変更する場合、Series と同じ長さの int の配列を指定します。

In [2]:
print(s.repeat([1, 2, 3]))
0    1
1    2
1    2
2    3
2    3
2    3
dtype: int64