sum
function.# In[1]
L = np.random.random(100)
sum(L)
# Out[1]
47.23340327381991
# In[2]
np.sum(L)
# Out[2]
47.23340327381991
sum
function is quite similar to Python's function, and the result is the same.# In[3]
big_array=np.random.rand(1000000)
%timeit sum(big_array)
%timeit np.sum(big_array)
# Out[3]
498 ms ± 66.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
2.06 ms ± 246 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
min
and max
, and Numpy's corresponding functions have similar syntax, but operate much more quickly# In[4]
min(big_array), max(big_array)
# Out[4]
(8.237773400088244e-07, 0.999999693122087)
# In[5]
np.min(big_array), np.max(big_array)
# Out[5]
(8.237773400088244e-07, 0.999999693122087)
# In[6]
%timeit min(big_array)
%timeit np.min(big_array)
# Out[6]
310 ms ± 83.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
1.31 ms ± 195 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
min
, max
, and several other Numpy aggregates, a shorter syntax is to use methods of the array object itself#In[7]
print(big_array.min(),big_array.max(),big_array.sum())
# Out[7]
8.237773400088244e-07 0.999999693122087 499601.2436555182
# In[8]
M=np.random.randint(0,10,(3,4))
print(M)
# Out[8]
[[7 9 2 7]
[1 0 5 2]
[7 5 9 5]]
axis
along which the aggregate is computed.# In[9]
M.min(axis=0)
# Out[9]
array([1, 0, 2, 2])
# In[10]
M.max(axis=1)
# Out[10]
array([9, 5, 9])
Useful Aggregation functions available in Numpy
Function | NaN-safe version | Description |
---|---|---|
np.sum | np.nansum | Compute sum of elements |
np.prod | np.nanprod | Compute product of elements |
np.mean | np.nanmean | Compute mean of elements |
np.std | np.nanstd | Compute standard deviation |
np.var | np.nanvar | Compute variance |
np.min | np.nanmin | Find minimum value |
np.max | np.nanmax | Find maximum value |
np.argmin | np.nanargmin | Find index of minimum value |
np.argmax | np.nanargmax | Find index of maximum value |
np.median | np.nanmedian | Compute median of elelments |
np.percentile | np.nanpercentile | Compute rank-based statistics of elements |
np.any | N/A | Evaluate whether any elements are true |
np.all | N/A | Evaluate whether all elements are true |