聚合函数
计算整个数组或指定轴上的总和、平均值、最小值、最大值和标准差。
聚合函数 是 CoddyKit 上的免费 Pandas & NumPy Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Pandas & NumPy Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Pandas & NumPy Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
What Is Aggregation?
Aggregation boils an array down to a few summary values, like a total or an average. NumPy's built-in functions do this in fast C, no loops needed.
import numpy as np
a = np.array([3, 7, 2, 9, 1, 6])
print('sum:', a.sum()) # 28
print('mean:', a.mean()) # 4.666...
print('max:', a.max()) # 9sum() and cumsum()
Use a.sum() for the total of every element, and np.cumsum for a running total — each spot holds the sum of everything up to it.
import numpy as np
a = np.array([1, 2, 3, 4, 5])
print(a.sum()) # 15
print(np.cumsum(a)) # [ 1 3 6 10 15]mean() and std()
a.mean() gives the average and a.std() the standard deviation. By default std divides by N; pass ddof=1 when your data is a sample.
import numpy as np
a = np.array([2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0])
print('mean:', a.mean()) # 5.0
print('std (pop):', a.std()) # 2.0
print('std (sample):', a.std(ddof=1)) # 2.138...min() and max() with argmin/argmax
a.min() and a.max() give the smallest and largest values. Want their positions instead? argmin and argmax return the index of each.
import numpy as np
a = np.array([3, 7, 2, 9, 1, 6])
print('min:', a.min(), 'at index', a.argmin()) # 1 at 4
print('max:', a.max(), 'at index', a.argmax()) # 9 at 3Aggregating Along an Axis
The axis argument picks which dimension to collapse: axis=0 gives one value per column, axis=1 one per row. Leave it off and you reduce the whole array.
import numpy as np
m = np.array([[1, 2, 3],
[4, 5, 6]])
print(m.sum(axis=0)) # [5 7 9] -- column sums
print(m.sum(axis=1)) # [ 6 15] -- row sums
print(m.mean(axis=0)) # [2.5 3.5 4.5]keepdims=True for Shape Preservation
Aggregating along an axis drops that dimension. Add keepdims=True to keep it as size 1 — essential when you want the result to broadcast back later.
import numpy as np
m = np.array([[1, 2, 3],
[4, 5, 6]])
row_sums = m.sum(axis=1, keepdims=True)
print(row_sums.shape) # (2, 1)
normed = m / row_sums
print(normed.round(3))
# [[0.167 0.333 0.5 ]
# [0.267 0.333 0.4 ]]NaN-Safe Aggregations
One NaN makes a normal sum or mean return NaN. The NaN-safe versions — np.nansum, np.nanmean, and friends — simply skip the missing values.
import numpy as np
a = np.array([1.0, np.nan, 3.0, np.nan, 5.0])
print(a.sum()) # nan
print(np.nansum(a)) # 9.0
print(np.nanmean(a)) # 3.0
print(np.nanmax(a)) # 5.0np.median and np.percentile
np.median gives the middle value and shrugs off outliers far better than the mean. np.percentile finds the value below which a given percent of data sits.
import numpy as np
a = np.array([1, 2, 3, 4, 100]) # outlier at 100
print('mean:', a.mean()) # 22.0 -- skewed
print('median:', np.median(a)) # 3.0 -- robust
print(np.percentile(a, [25, 50, 75])) # [ 2. 3. 4.]np.any() and np.all()
np.any returns True if at least one element passes a condition; np.all returns True only if every element does. Both can check per row or column.
import numpy as np
a = np.array([1, -2, 3, -4])
print(np.any(a < 0)) # True (some are negative)
print(np.all(a > 0)) # False (not all are positive)
# Row-wise check on 2D
m = np.array([[1, 2], [-1, 3]])
print(np.all(m > 0, axis=1)) # [ True False]np.count_nonzero()
np.count_nonzero counts how many elements aren't zero — or how many are True. Pass it a condition like a > 5 to count matches cleanly.
import numpy as np
a = np.array([3, 0, 7, 0, 2, 0])
print(np.count_nonzero(a)) # 3
print(np.count_nonzero(a > 2)) # 2 (elements 3 and 7)
m = np.array([[0, 1], [1, 1]])
print(np.count_nonzero(m, axis=0)) # [1 2]np.unique() for Distinct Values
np.unique returns the sorted distinct values. Add return_counts=True and you also get how often each appears — an instant frequency table.
import numpy as np
a = np.array([3, 1, 4, 1, 5, 9, 2, 6, 5, 3])
uniq, counts = np.unique(a, return_counts=True)
print(uniq) # [1 2 3 4 5 6 9]
print(counts) # [2 1 2 1 2 1 1]Quick Check
Test your understanding of NumPy aggregation functions from this lesson.
Lesson Recap
Great job! NumPy aggregations summarise arrays in fast C, the axis argument picks what to collapse, and NaN-safe versions skip missing values. Next: broadcasting.
常见问题解答
「聚合函数」课时是免费的吗?
是的 — 「聚合函数」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Pandas & NumPy Academy 课程的其余内容,请升级到 CoddyKit PRO。 Pandas & NumPy Academy 课程共包含 4 节课。
「聚合函数」这节课中我会学到什么?
计算整个数组或指定轴上的总和、平均值、最小值、最大值和标准差。 你通过在浏览器中直接运行的动手代码来练习 Pandas & NumPy Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Pandas & NumPy Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Pandas & NumPy Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「聚合函数」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Pandas & NumPy Academy 课中编写并运行代码吗?
能。每节 Pandas & NumPy Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。