iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Aggregations

Reductions collapse an axis (or the whole array) into a single value. NumPy ships sum, mean, std, min, max, argmin, argmax, plus all-row / all-column variants via the axis argument.

NumPy + Pandas aggregations

EXAMPLE
import numpy as np
import pandas as pd

# 1) NumPy reductions
m = np.arange(12).reshape(3, 4)
print(m.sum())            # scalar — whole array
print(m.sum(axis=0))      # column sums  (length 4)
print(m.sum(axis=1))      # row sums     (length 3)
print(m.cumsum(axis=1))   # running total per row

print(m.mean(), m.std(ddof=0))
print(m.min(axis=0), m.argmin(axis=0))

# 2) NaN-aware reductions — ignore missing values
x = np.array([1.0, np.nan, 3.0])
print(np.nanmean(x))      # 2.0
print(np.nansum(x))       # 4.0

# 3) Pandas series reductions
s = pd.Series([10, 20, 30, np.nan, 50])
s.sum(), s.mean(), s.median(), s.std()
s.count()                  # non-null count
s.value_counts()

# 4) DataFrame reductions
df = pd.DataFrame({
    'team':   ['A','A','B','B','B'],
    'goals':  [1, 3, 0, 2, 5],
    'shots':  [4, 6, 3, 5, 7],
})
df.sum(numeric_only=True)
df.describe()

# 5) Group-wise — agg with named outputs
df.groupby('team').agg(
    total_goals = ('goals', 'sum'),
    avg_goals   = ('goals', 'mean'),
    n           = ('goals', 'size'),
    accuracy    = ('goals', lambda g: g.sum() / df.loc[g.index, 'shots'].sum()),
)

# 6) Multi-column, multi-fn — pivot-table style
df.pivot_table(
    index='team',
    values=['goals', 'shots'],
    aggfunc=['sum', 'mean'],
)

Why it matters

Always specify axis explicitly on multi-D arrays. “The wrong axis” bugs are silent — results have the wrong shape but no error, then propagate downstream.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.sum(), a.mean(), a.std())
print(a.sum(axis=0))       # column sums
print(a.sum(axis=1))       # row sums
Try it Yourself »

Exercise

Sum across rows (axis-1).

a.sum( =1)

Discussion

Loading…