Listen up. If you're doing numerical computing in Python, you need to understand Logs and Summations in Python. NumPy is the backbone of the entire scientific Python ecosystem, and using it correctly is the difference between a script that takes seconds versus hours.
1Numpy logs summations Part 1
NumPy separates element-wise arithmetic from aggregation, and the distinction trips up a lot of newcomers. np.add(arr1, arr2) combines two arrays position by position and returns an array of the same shape, while np.sum(arr) collapses a single array down to one scalar total. On a multi-dimensional array, np.sum() flattens everything by default, but passing axis=0 sums down each column and axis=1 sums across each row ā the axis you choose determines which dimension gets collapsed and which one survives in the output shape.
Running totals are a related but separate operation: np.cumsum() returns an array the same size as the input, where each position holds the sum of every element up to and including that index. It's the tool for tracking a balance over time rather than reducing data to a single number.
Logarithms round out this lesson's toolkit. NumPy ships ufuncs for the three bases that come up constantly ā np.log() for the natural log, np.log2() for base 2, and np.log10() for base 10 ā but has no built-in ufunc for an arbitrary base like 3. To get one, you wrap Python's math.log with np.frompyfunc(log, 2, 1), turning an ordinary two-argument function into something that broadcasts across arrays the way native ufuncs do.
# Example
import numpy as np
print("Running NumPy...")Matrix operations completed.
2Step-by-Step Breakdown
Let's look at advanced aggregations and transformations. Often, we need to sum up vast arrays of data, or compress large numbers using logarithms.
We've seen np.add(arr1, arr2) for element-wise addition. But if you want to add all the numbers INSIDE a single array together to get a total, you use np.sum().
What is the primary difference between np.add() and np.sum()?
- āThey are exactly the same; np.add is just an alias for np.sum.
- ānp.sum only works on 1D vectors, while np.add only works on matrices.
- ānp.add performs element-by-element addition between two arrays. np.sum adds all the elements within an array together.
When dealing with multi-dimensional matrices, np.sum() flattens the whole matrix and returns one total. If you want to sum across rows or columns, use the axis parameter.
You can also do a cumulative sum with np.cumsum(). This returns an array where each element is the sum of itself and all previous elements. Great for tracking running totals.
If arr = np.array([5, 5, 5]), what will np.cumsum(arr) output?
- ā[5, 10, 15]
- ā15
- ā[15, 15, 15]
Now let's look at Logarithms. Logs are the mathematical inverse of exponents. NumPy provides ufuncs to calculate logs at base 2 (log2), base 10 (log10), and the natural log (log).
NumPy does NOT provide a built-in ufunc for arbitrary bases (like base 3). To do that, you must use frompyfunc with the math.log module to build your own log generator.
If you want to calculate the natural logarithm (base e) of every element in an array, which NumPy ufunc should you use?
- ānp.ln()
- ānp.log()
- ānp.loge()
Now, prepare yourself. We are about to enter the ADA Defense Protocol. Ensure you understand array summation and axes.
ADA DEFENSE: If you have a 2D matrix representing 5 students (rows) and their scores on 3 tests (columns), which parameter would you pass to np.sum() to get the total score for EACH student individually?
- āaxis=0
- āaxis=1
- āaxis=all
Threat neutralized. Matrix aggregation successful. Mathematical transformations complete.
Compute a Real Running Total. Finish running_total(): use np.cumsum() so each output is the sum of itself and everything before it.
Level Up š
Advanced cheat sheets, SEO tricks, and interview prep for this topic.
Browser Support
Fully supported.
Fully supported.
Fully supported.
Fully supported.
Accessibility (A11y)
1Readable Aggregation Code
Passing axis explicitly (np.sum(mat, axis=1)) instead of relying on the default makes the intent of a reduction immediately clear to anyone reading the code later, rather than requiring them to trace shapes by hand.
# Prefer:
row_totals = np.sum(mat, axis=1)
# Over an unlabeled call that leaves the axis to guessworkSEO Implications
- 1
High-Intent Reference Queries
Searches like 'numpy sum axis explained' and 'numpy log base 10' are common among learners debugging aggregation code, so accurate, example-driven coverage of axis behavior and log ufuncs performs well in organic search.
Best Practices
Always Pass axis Explicitly on Multi-Dimensional Arrays
Relying on the default (which flattens the whole array) is a common source of silently wrong totals; state axis=0 or axis=1 so the reduction direction is unambiguous.
Reach for np.log1p() Near Zero
np.log(x) loses precision or blows up (returns -inf) as x approaches 0; np.log1p(x) computes log(1+x) with far better numerical precision for small values.
Frequent Bugs
Calling np.sum() on a matrix expecting per-row or per-column totals, but forgetting the axis argument, so it silently flattens everything into a single grand total.
Specify axis=0 for column-wise sums or axis=1 for row-wise sums, and check arr.sum(axis=...).shape matches what you expect before trusting the result.
Real-World Examples
Per-Student Score Totals
A grading script stores 5 students x 3 test scores in a (5, 3) matrix and needs each student's total, not one grand total for the whole class.
scores = np.array([[80, 90, 70], [60, 75, 85], [95, 88, 92], [70, 60, 65], [100, 95, 90]])
# Wrong: one number for everyone
total = np.sum(scores)
# Correct: one total per student (per row)
per_student = np.sum(scores, axis=1)
print(per_student) # [240 220 275 195 285]