NumPy – Sum Function
The sum operation is one of the most basic and frequently used operations in data analysis and scientific computing.
In NumPy, the np.sum() function allows you to quickly calculate the sum of array elements in different ways.
It is widely used in:
- Data science
- Machine learning
- Statistics
- Financial analysis
What is NumPy Sum?
The sum function returns the total of all elements in an array or along a specific axis.
Simply: It adds numbers inside arrays efficiently.
Import NumPy
import numpy as np
1. Sum of All Elements
import numpy as np
A = np.array([[1, 2],
[3, 4]])
result = np.sum(A)
print(result)
Output:
10
2. Sum by Axis (Rows vs Columns)
Sum of Columns (axis=0)
import numpy as np
A = np.array([[1, 2],
[3, 4]])
result = np.sum(A, axis=0)
print(result)
Output:
[4 6]
Sum of Rows (axis=1)
import numpy as np
A = np.array([[1, 2],
[3, 4]])
result = np.sum(A, axis=1)
print(result)
Output:
[3 7]
3. Sum of 1D Array
import numpy as np
A = np.array([10, 20, 30, 40])
print(np.sum(A))
Output:
100
4. Sum with Floating Numbers
import numpy as np
A = np.array([1.5, 2.5, 3.0])
print(np.sum(A))
Output:
7.0
5. Conditional Sum (Using Boolean Masking)
import numpy as np
A = np.array([10, 15, 20, 25, 30])
print(np.sum(A[A > 20]))
Output:
55
6. Sum in Multi-Dimensional Arrays
import numpy as np
A = np.array([
[[1, 2], [3, 4]],
[[5, 6], [7, 8]]
])
print(np.sum(A))
Output:
36
7. Using keepdims Parameter
import numpy as np
A = np.array([[1, 2],
[3, 4]])
print(np.sum(A, axis=1, keepdims=True))
Output:
[[3]
[7]]
Real-World Applications
1. Data Science
- Total sales calculation
- Dataset aggregation
2. Machine Learning
- Loss calculation
- Gradient updates
3. Finance
- Revenue summation
- Profit analysis
4. Statistics
- Mean calculation (basis of sum)
- Data aggregation
Why Use NumPy Sum?
Using NumPy provides:
- Fast computation
- Optimized C-based operations
- Easy axis-based calculations
- Works with large datasets
Combined with Python, it becomes essential for data analysis and AI workflows.
Summary
NumPy provides a powerful way to calculate sums using:
np.sum(array, axis=...)
It supports multi-dimensional arrays, conditional sums, and performance optimization.
Conclusion
The NumPy sum function is a fundamental tool in data science and numerical computing. It simplifies aggregation tasks and improves performance in real-world applications.


0 Comments