Pythonのnumpy.cumsum()
Pythonのnumpyのcumsum()関数は、指定した軸に沿った要素の累積和を返します。
Python numpy cumsum() 構文
cumsum() メソッドの構文は次のとおりです:
cumsum(array, axis=None, dtype=None, out=None)
- 配列はndarrayまたは入れ子リストのような配列に似たオブジェクトであることができます。
- 軸パラメータは累積和が計算される軸を定義します。軸が指定されていない場合、配列は平坦化され、結果配列の累積和が計算されます。
- dtype パラメータは、float や int などの出力データ型を定義します。
- 出力の出オプションのパラメータは、結果のための配列を指定するために使用されます。
Python numpy cumsum() の例
Numpy配列の要素の累積和を計算するいくつかの例を見てみましょう。
1. 軸なしでのNumpy配列要素の累積和
import numpy as np
array1 = np.array(
[[1, 2],
[3, 4],
[5, 6]])
total = np.cumsum(array1)
print(f'Cumulative Sum of all the elements is {total}')
出力: すべての要素の累積和は [ 1 3 6 10 15 21 ] です。ここでは、配列が最初に [ 1 2 3 4 5 6 ] にフラット化されます。それから累積和が計算され、[ 1 3 6 10 15 21 ] が得られます。
2. 軸に沿った累積和
import numpy as np
array1 = np.array(
[[1, 2],
[3, 4],
[5, 6]])
total_0_axis = np.cumsum(array1, axis=0)
print(f'Cumulative Sum of elements at 0-axis is:\n{total_0_axis}')
total_1_axis = np.cumsum(array1, axis=1)
print(f'Cumulative Sum of elements at 1-axis is:\n{total_1_axis}')
出力 :
Cumulative Sum of elements at 0-axis is:
[[ 1 2]
[ 4 6]
[ 9 12]]
Cumulative Sum of elements at 1-axis is:
[[ 1 3]
[ 3 7]
[ 5 11]]
3. 累積和配列のデータ型を指定する
import numpy as np
array1 = np.array(
[[1, 2],
[3, 4],
[5, 6]])
total_1_axis = np.cumsum(array1, axis=1, dtype=float)
print(f'Cumulative Sum of elements at 1-axis is:\n{total_1_axis}')
出力 :
Cumulative Sum of elements at 1-axis is:
[[ 1. 3.]
[ 3. 7.]
[ 5. 11.]]
参照: API ドキュメント
