集約関数
配列全体、または特定のaxisに沿って、合計、平均、最小値、最大値、標準偏差を計算します。
「集約関数」はCoddyKit上の無料Pandas & NumPy Academyレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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.
よくある質問
「集約関数」レッスンは無料ですか?
はい。「集約関数」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Pandas & NumPy Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Pandas & NumPy Academyコースには全4レッスンが含まれています。
「集約関数」で何を学びますか?
配列全体、または特定のaxisに沿って、合計、平均、最小値、最大値、標準偏差を計算します。 ブラウザで直接実行するハンズオンコードでPandas & NumPy Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Pandas & NumPy Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのPandas & NumPy Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。
「集約関数」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このPandas & NumPy Academyレッスンでコードを書いて実行できますか?
はい。すべてのPandas & NumPy Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。