Series Basics
Series Aggregate
Reduce a list of values to a single sum and mean with a manual accumulator
loop. The pandas version calls .sum() and .mean() directly on a Series,
showing how aggregations collapse the entire index-and-values structure to a
scalar.
By hand
With pandas
s.sum() and s.mean() reduce the Series to scalars. int() and float()
convert the numpy scalars to plain Python types for a stable RESULT.
naive.py
values = [4, 7, 2, 9, 3]
total = 0
for v in values:
total += v
mean = round(total / len(values), 2)
print('RESULT:', (total, mean))
library.py
import pandas as pd
from dalib.display import set_display
set_display()
values = [4, 7, 2, 9, 3]
s = pd.Series(values)
total = int(s.sum())
mean = round(float(s.mean()), 2)
print('index:', s.index.tolist())
print('values:', s.tolist())
print('dtype:', s.dtype)
print('sum:', total)
print('mean:', mean)
print('RESULT:', (total, mean))
index: [0, 1, 2, 3, 4]
values: [4, 7, 2, 9, 3]
dtype: int64
sum: 25
mean: 5.0
RESULT: (25, 5.0)
Implementation notes
s.sum()ands.mean()return numpy scalars (np.int64,np.float64). Wrapping withint()/float()converts them to Python natives, avoiding repr differences across numpy versions (see the NumPysum-and-meanlesson).- Aggregation methods ignore the index and operate only on the values array.
Any index — default
RangeIndexor string labels — produces the same sum and mean. - Other common aggregations on a Series:
.min(),.max(),.std(),.median(),.count(). All reduce to a scalar and share the same numpy-scalar return type pattern. - Cross-reference:
sum-and-mean(python-numpy ch05) for the NumPy array version;list-sum-mean(python-data-basics) for the plain Python version.