Pythonのnumpy.sum()

Python numpyのsum()関数は、指定された軸に沿って配列要素の合計を取得するために使用されます。

Pythonのnumpyのsum()関数の構文

PythonのNumPyのsum()メソッドの構文は次のようになります。

sum(array, axis, dtype, out, keepdims, initial)
  • The array elements are used to calculate the sum.
  • If the axis is not provided, the sum of all the elements is returned. If the axis is a tuple of ints, the sum of all the elements in the given axes is returned.
  • We can specify dtype to specify the returned output data type.
  • The out variable is used to specify the array to place the result. It’s an optional parameter.
  • The keepdims is a boolean parameter. If this is set to True, the axes which are reduced are left in the result as dimensions with size one.
  • The initial parameter specifies the starting value for the sum.

Pythonのnumpyのsum()関数の例を一つ示します。

「numpyのsum()関数のいくつかの例を見てみましょう。」

配列の要素の合計

sum()関数に配列のみを渡すと、配列がフラット化され、すべての要素の合計が返されます。

import numpy as np

array1 = np.array(
    [[1, 2],
     [3, 4],
     [5, 6]])

total = np.sum(array1)
print(f'Sum of all the elements is {total}')

結果:全ての要素の合計は21です。

2.配列要素の軸に沿った合計

軸の値を指定する場合、その軸に沿った要素の合計が返されます。配列の形状が(X, Y)の場合、0軸に沿った合計は形状(1, Y)になります。1軸に沿った合計は形状(1, X)になります。

import numpy as np

array1 = np.array(
    [[1, 2],
     [3, 4],
     [5, 6]])

total_0_axis = np.sum(array1, axis=0)
print(f'Sum of elements at 0-axis is {total_0_axis}')

total_1_axis = np.sum(array1, axis=1)
print(f'Sum of elements at 1-axis is {total_1_axis}')

出力:

Sum of elements at 0-axis is [ 9 12]
Sum of elements at 1-axis is [ 3  7 11]

3. 合計の出力データ型の指定

import numpy as np

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

total_1_axis = np.sum(array1, axis=1, dtype=float)
print(f'Sum of elements at 1-axis is {total_1_axis}')

出力:1軸の要素の合計は [3. 7.] です。

4. 合計の初期値

import numpy as np

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

total_1_axis = np.sum(array1, axis=1, initial=10)
print(f'Sum of elements at 1-axis is {total_1_axis}')

出力結果:1軸の要素の合計は[13 17]です。参考:APIドキュメント

コメントを残す 0

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