numpy.sum(a,axis=None,dtype=None,out=None,keepdims, initial, where)
Return sum of elements across given axis.
a | array, elements to get the sum value |
axis | Int (optional ), or tuple, default is None, will sum all the elements. If axis given then across the axis is returned. |
dtype | data-type( Optional ), Data Type of returned array or value. |
out | Optional. If given then output to be stored. Must be of same time as of the output |
keepdims | Bool ( Optional ), output matches to the input array dimension. |
where | Optional, Elements to include for calculation of Sum |
initial | Optional, int, Initial value of sum. This value will be added to our final output |
import numpy as np
# my_data=np.random.randint(2,high=7,size=(3,3),dtype='int16')
my_data=np.array([[6, 3, 2], [2, 6, 2], [6, 2, 3]])
print(my_data)
Output
[[6 3 2]
[2 6 2]
[6 2 3]]
print("sum() : ", my_data.sum())
print("sum(axis=0):", my_data.sum(axis=0))
print("sum(axis=1):", my_data.sum(axis=1))
Output
sum() : 32
sum(axis=0): [14 11 7]
sum(axis=1): [11 10 11]
print("sum(axis=1,dtype=np.int8) : ", my_data.sum(axis=1,dtype=np.int8))
print("sum(axis=1,dtype=np.int32) : ", my_data.sum(axis=1,dtype=np.int32))
print("sum(axis=1,dtype=np.float64) : ", my_data.sum(axis=1,dtype=np.float64))
print("sum(axis=1,dtype=np.complex128) : ", my_data.sum(axis=1,dtype=np.complex128))
Output
sum(axis=1,dtype=np.int8) : [11 10 11]
sum(axis=1,dtype=np.int32) : [11 10 11]
sum(axis=1,dtype=np.float64) : [11. 10. 11.]
sum(axis=1,dtype=np.complex128) : [11.+0.j 10.+0.j 11.+0.j])
print("sum(keepdims=True) : ", my_data.sum(keepdims=True))
print("sum(keepdims=False) : ", my_data.sum(keepdims=False))
Output
sum(keepdims=True) : [[43]]
sum(keepdims=False) : 43
x = np.zeros(3,dtype=int)
print(my_data.sum(axis=0,out=x))
print(x)
Output
[14 11 7]
[14 11 7]
Without using axis
y = np.array(1)
print(my_data.sum(out=y))
print(y)
Output
32
32
By using where we can say which elements to use and which elements not to use ( by setting True or False ) .
print(my_data.sum(where=[True, False,True]))
Output
21
Using axis with where
print(my_data.sum(axis=1,where=[True, False,True]))
print(my_data.sum(axis=0,where=[True, False,True]))
Output
[8 4 9]
[14 0 7]
print(my_data.sum(initial=10))
Output
42
Numpy
mean()
max()
min()
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.