Series Basics
Series Arithmetic Alignment
Add two label->value mappings by matching on their shared keys. A loop iterates
over the key list and sums corresponding values, making the label-matching step
explicit. With pandas, s1 + s2 aligns on index labels automatically before
operating.
By hand
With pandas
s1 + s2 aligns both Series on their index labels first, then adds the
matched values. The snapshot shows both input value lists, then the aligned
result index, values, and dtype.
naive.py
labels = ['a', 'b', 'c', 'd']
d1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
d2 = {'a': 10, 'b': 20, 'c': 30, 'd': 40}
result = {}
for k in labels:
result[k] = d1[k] + d2[k]
print('RESULT:', result)
library.py
import pandas as pd
from dalib.display import set_display
set_display()
labels = ['a', 'b', 'c', 'd']
s1 = pd.Series([1, 2, 3, 4], index=labels)
s2 = pd.Series([10, 20, 30, 40], index=labels)
result = s1 + s2
print('s1 values:', s1.tolist())
print('s2 values:', s2.tolist())
print('index:', result.index.tolist())
print('values:', result.tolist())
print('dtype:', result.dtype)
print('RESULT:', dict(zip(result.index.tolist(), result.tolist())))
s1 values: [1, 2, 3, 4]
s2 values: [10, 20, 30, 40]
index: ['a', 'b', 'c', 'd']
values: [11, 22, 33, 44]
dtype: int64
RESULT: {'a': 11, 'b': 22, 'c': 33, 'd': 44}
Implementation notes
- Pandas aligns on index labels before applying any arithmetic operator. When both Series share the same index, every label matches and the result has the same index. When labels differ, any label present in only one Series produces NaN in the result — the operation succeeds but marks the missing value explicitly.
result.tolist()returns Python-native ints, so the zipped dict matches the naive RESULT exactly without numpy scalar repr differences.- The same alignment rule applies to subtraction, multiplication, and division; it also governs how DataFrame columns combine during row-wise operations.