Home  >  Article  >  Backend Development  >  How to do accumulation in python

How to do accumulation in python

尚
Original
2019-06-26 15:23:1316373browse

How to do accumulation in python

In Python, accumulation can be achieved using the function sum(),

Example:

numpy.sum(A)---all in the array Sum of elements, A---Array

import numpy as np
a = np.array([[1,3,6],[9,5,6]])
b = np.sum(a)
print(b)

Print

How to do accumulation in python

numpy.sum(A, axis=1)---The sum of all elements in the array and, the sum of the elements of a row with axis=1

import numpy as np
a = np.array([[1,3,6],[9,5,6]])
b = np.sum(a , axis=1)
print(b)

Introduction to sum function:

Python’s own sum function (or sum function in Numpy),
When there are no parameters, add all;
axis=0, add by columns;
axis=1, add by rows;

import numpy as np  
#python中自带的sum  
print(sum([[1,2,3],[4,5,5]]))  
print(sum([[1,2,3],[4,5,5]],axis=0))  
print(sum([[1,2,3],[4,5,5]],axis=1))  
#Numpy中的sum  
a = np.sum([[1,2,3], [4,5,5]]) #无参  
print(a)  
print(a.shape)  
a = np.sum([[1,2,3], [4,5,5]],axis=0) #axis=0, 按列相加  
print(a)  
print(a.shape)  
a = np.sum([[1,2,3], [4,5,5]],axis=1) #axis=1, 按行相加  
print(a)  
print(a.shape)
20
[5 7 8]
[ 6 14]
20
()
[5 7 8]
(3,)
[ 6 14]
(2,)

For more Python related technical articles, please visit Python tutorial column to learn!

The above is the detailed content of How to do accumulation in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn