šŸš€ LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
šŸŽ“ COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
HTML MASTER CLASS /// LEARN TAGS /// BUILD STRUCTURE /// SEMANTIC WEB /// HTML MASTER CLASS /// LEARN TAGS ///

Logs and Summations in Python

Learn about Logs and Summations in this comprehensive Python tutorial. Understand the strict architectural difference between element-wise array addition and matrix aggregation, master cumulative sums, and effectively apply logarithmic scale transformations.

⚔ Total XP: 0|šŸ’» numpy XP: 0

Skill Matrix

UNLOCK NODES BY LEARNING NEW TAGS.

System Hub

Core logic.

Quick Quiz //

What does np.sum(mat, axis=1) compute for a 2D array?


šŸš€ LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
šŸŽ“ COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.

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...")
localhost:3000
Jupyter Notebook / Console Output
Code Executed Successfully
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

ChromeSupported

Fully supported.

FirefoxSupported

Fully supported.

SafariSupported

Fully supported.

EdgeSupported

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 guesswork

SEO 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

THE BUG

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.

THE FIX

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]

Interview Prep

?Frequently Asked Questions

Pascual Vila

Pascual Vila

Frontend Instructor // Code Syllabus

Common Pitfalls & Errors

The Error //

Taking the log of zero or a negative number

arr = np.array([10, 0, -5]) # Silently produces [2.303 -inf nan] with a warning res = np.log(arr) # Safer: mask out non-positive values first safe = arr[arr > 0] res = np.log(safe)

The Solution //

np.log(0) returns -inf with a RuntimeWarning, and np.log() of a negative number returns NaN instead of raising an exception, so bad values silently propagate downstream. Filter or clip the array before taking the log.

The Error //

Forgetting axis and getting a flattened grand total instead of per-row/per-column sums

mat = np.array([[1, 2], [3, 4]]) # Wrong: one number for the whole matrix total = np.sum(mat) # 10 # Correct: one total per row row_totals = np.sum(mat, axis=1) # [3 7]

The Solution //

np.sum(matrix) with no axis argument collapses every dimension into one scalar. If you wanted totals per row or column, you must pass axis explicitly.

Lesson Glossary

[01]np.sum()

An aggregation function that adds all elements in an array, returning a single scalar total unless an axis is specified.

Code Preview
// np.sum() context

[02]np.cumsum()

Cumulative sum; returns an array of the same size containing the running total of elements.

Code Preview
// np.cumsum() context

[03]np.log10()

A ufunc that applies the base-10 logarithm element-wise to an array.

Code Preview
// np.log10() context

Continue Learning