Сумма частей массива python

Функция numpy.sum() в Python

Функция numpy.sum() в Python используется для получения суммы элементов массива по заданной оси.

Синтаксис функции

sum(array, axis, dtype, out, keepdims, initial)
  • Array (элементы массива) используются для вычисления суммы.
  • Если axis не указана, возвращается сумма всех элементов. Если axis представляет собой кортеж целых чисел, возвращается сумма всех элементов в данных осях.
  • Мы можем указать dtype, чтобы указать тип возвращаемых выходных данных.
  • Переменная out используется для указания массива для размещения результата. Это необязательный параметр.
  • Keepdims – это логический параметр. Если установлено значение True, уменьшенные оси останутся в результате с размером один.
  • Initial (первоначальный параметр) указывает начальное значение суммы.

Примеры

Давайте посмотрим на некоторые примеры функции numpy sum().

1. Сумма всех элементов в массиве

Если мы передаем в функцию 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 ')

Вывод: сумма всех элементов равна 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_1_axis = np.sum(array1, axis=1) print(f'Sum of elements at 1-axis is ')
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 ')

Выход: сумма элементов на 1 оси равна [3. 7.].

Читайте также:  Compare date with python

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 ')

Выход: сумма элементов на 1 оси равна [13 17].

Источник

sum parts of numpy.array

I want to sum the first two values of the first row: 1+2 = 3 , then next two values: 3+4 = 7 , and then 5+6 = 11 , and so on for every row. My desired output is this:

array([[ 3, 7, 11], [15, 19, 23], [ 8, 13, 17]]) 
def sum_chunks(x, chunk_size): rows, cols = x.shape x = x.reshape(x.size / chunk_size, chunk_size) return x.sum(axis=1).reshape(rows, cols/chunk_size) 

3 Answers 3

This takes the array formed by every even-indexed column ( ::2 ), and adds it to the array formed by every odd-indexed column ( 1::2 ).

How would you generalize this? You can do np.sum([a[:,i::n] for i in xrange(n)], 0) if you might need to sum n consecutive columns, for example.

Your solution is shorter and easier to read, but I timed it and my initial solutions is considerably faster.

@Akavall: the code in my answer is faster than your sum_chunks specifically for n=2 . For larger n , other solutions may be faster. My comment solution is an example of a solution, but I was not aiming to optimize.

When I have to do this kind of stuff, I prefer reshaping the 2D array into a 3D array, then collapse the extra dimension with np.sum . Generalizing it to n-dimensional arrays, you could do something like this:

def sum_chunk(x, chunk_size, axis=-1): shape = x.shape if axis < 0: axis += x.ndim shape = shape[:axis] + (-1, chunk_size) + shape[axis+1:] x = x.reshape(shape) return x.sum(axis=axis+1) >>> a = np.arange(24).reshape(4, 6) >>> a array([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23]]) >>> sum_chunk(a, 2) array([[ 1, 5, 9], [13, 17, 21], [25, 29, 33], [37, 41, 45]]) >>> sum_chunk(a, 2, axis=0) array([[ 6, 8, 10, 12, 14, 16], [30, 32, 34, 36, 38, 40]]) 

Источник

Оцените статью