Pythonのnumpy.cumsum()

Pythonのnumpy cumsum()関数は、指定した軸に沿って要素の累積和を返します。

Pythonのnumpy cumsum()の構文

cumsum()メソッドの構文は次のとおりです。

cumsum(array, axis=None, dtype=None, out=None)
  • The array can be ndarray or array-like objects such as nested lists.
  • The axis parameter defines the axis along which the cumulative sum is calculated. If the axis is not provided then the array is flattened and the cumulative sum is calculated for the result array.
  • The dtype parameter defines the output data type, such as float and int.
  • The out optional parameter is used to specify the array for the result.

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ドキュメント

コメントを残す 0

Your email address will not be published. Required fields are marked *