The Series: Pandas

Published by Brayan K

A Pandas Series is a one-dimensional labelled array — a single column of data where every value is paired with an index label, like a smarter, faster version of a Python list.

Part of the free Pandas course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Keep each value attached to its label

A Series has one axis of labels and one dtype for its values. Its index identifies observations; its name describes the whole Series. Labels are not automatically row positions. Start with quantities whose item labels matter, so changing their order cannot silently change their meaning.

import pandas as pd

quantity = pd.Series([4, 2, 7], index=["pen", "book", "folder"],
                     dtype="int64", name="quantity")
print(quantity.index.tolist())
print(quantity.tolist())
print(quantity.name, quantity.ndim, quantity.shape)
print(int(quantity.loc["book"]), int(quantity.iloc[0]))

# ✅ Expected output:
# ['pen', 'book', 'folder']
# [4, 2, 7]
# quantity 1 (3,)
# 2 4

loc selects by label and iloc selects by position in those two scalar reads. The complete indexing and slicing rules belong to loc vs iloc: Label vs Position. Here the point is that the label book remains attached to its quantity.

import pandas as pd

pd.Series([4, 2], index=["pen"], dtype="int64")

# ✅ Expected error:
# ValueError: Length of values (2) does not match length of index (1)

A scalar can be repeated across an explicitly supplied index. A dictionary instead associates values with keys and can be selected/reordered by the requested index. Those are different constructor contracts; they are not positional zips.

Arithmetic matches labels, even when the orders differ

import pandas as pd

received = pd.Series([10, 6], index=["pen", "book"], dtype="int64")
used = pd.Series([2, 3], index=["book", "pen"], dtype="int64")
remaining = received - used
print(int(remaining.loc["pen"]), int(remaining.loc["book"]))
print((received.to_numpy() - used.to_numpy()).tolist())

# ✅ Expected output:
# 7 4
# [8, 3]

The labelled subtraction pairs pen with pen and book with book. Converting to NumPy removes that label relationship and makes the second subtraction positional. It can produce perfectly valid numbers for the wrong items. Use positional arrays only when that is the intended contract.

import pandas as pd

left = pd.Series([4, 8], index=["pen", "book"], dtype="int64")
right = pd.Series([2, 1], index=["book", "clip"], dtype="int64")
result = left + right
print(result.index.tolist())
print(result.isna().to_dict())
print(float(result.loc["book"]))

# ✅ Expected output:
# ['book', 'clip', 'pen']
# {'book': False, 'clip': True, 'pen': True}
# 10.0

Ordinary arithmetic aligns on the union of labels. A label found on only one side has no matching operand, so its result is missing. Do not fill that gap with zero unless zero represents the absent observation in your domain. Handling Missing Data (NaN, fillna, dropna) owns that decision.

import pandas as pd

quantity = pd.Series([4, 2], index=["pen", "book"], dtype="int64")
ordered = quantity.reindex(["book", "pen"])
print(ordered.index.tolist(), ordered.tolist())
print(quantity.index.tolist(), quantity.tolist())

# ✅ Expected output:
# ['book', 'pen'] [2, 4]
# ['pen', 'book'] [4, 2]

The example makes a requested report order explicit and keeps the original Series unchanged. The Index: set_index, reset_index & reindex owns the broader reindexing API, including adding labels and index construction.

A label is not guaranteed to identify exactly one observation

import pandas as pd

quantity = pd.Series([4, 2, 7], index=["pen", "pen", "book"], dtype="int64")
selected = quantity.loc["pen"]
print(quantity.index.is_unique)
print(type(selected).__name__, selected.tolist())

# ✅ Expected output:
# False
# Series [4, 2]

Pandas permits duplicate labels. If your application treats item labels as unique keys, test index.is_unique at the boundary rather than assuming a scalar selection. A repeated label can also make arithmetic alignment expand matches; rejecting it is often clearer than guessing which observation the user intended.

import pandas as pd

quantity = pd.Series([4, 2], index=["pen", "book"], dtype="int64")
print("pen" in quantity, 4 in quantity)
print(bool(quantity.isin([4]).any()))

# ✅ Expected output:
# True False
# True

The in operator checks Series labels. Use a value comparison or isin when the question concerns the values. Naming the question first avoids treating two different forms of membership as interchangeable.

import pandas as pd

quantity = pd.Series([4, 2], index=["pen", "book"], dtype="int64")
print(quantity.loc["clip"])

# ✅ Expected error:
# KeyError: 'clip'

A Series has one dtype, and missingness is part of that representation

import pandas as pd

quantity = pd.Series([4, None, 7], index=["pen", "book", "folder"], dtype="Int64")
print(str(quantity.dtype))
print(quantity.isna().tolist())
print(int(quantity.count()), len(quantity))
print(int(quantity.sum()))

# ✅ Expected output:
# Int64
# [False, True, False]
# 2 3
# 11

The capital-I Int64 extension dtype permits missing integer values. Plain int64 and Int64 are different types. This example chooses a type explicitly instead of relying on changing inference defaults; Data Types & astype owns conversions and Handling Missing Data (NaN, fillna, dropna) owns missing-value operations.

import pandas as pd

quantity = pd.Series([4, 0], dtype="int64")
if quantity:
    print("has stock")

# ✅ Expected error:
# ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Ask the intended question explicitly: whether any value matches, whether all values match, or whether the Series has no entries. Those are different answers. Filtering with Boolean Masks owns combining conditions and filtering observations.

Guided exercise: align usage to a declared report order

Fill the literal hints. Keep labels in the calculation and make the report order explicit.

import pandas as pd

received = pd.Series([10, 6], index=["pen", "book"], dtype="int64")
used = pd.Series([2, 3], index=["book", "pen"], dtype="int64")
# 👉 replace ___ with reindex
aligned = used.___(received.___)
# 👉 replace ___ with index
# 👉 replace ___ with aligned
remaining = received - ___
print(remaining.index.tolist(), remaining.tolist())

# ✅ Expected output:
# ['pen', 'book'] [7, 4]

Build brief: reject a stock report whose labels do not match

Implement stock_balance(received, used). Require two Series with unique, nonempty string labels, nonnegative int64 quantities and exactly the same set of item labels. Reorder used to match received, subtract by labels and reject any negative remaining quantity. Return a Series named remaining in received order, without changing either input. Empty matching Series are valid.

This contract treats an absent item as invalid input, not as zero. It also rejects nullable or floating dtypes instead of coercing them. The nonnegative signed-int64 inputs keep a valid subtraction within that dtype’s range; a negative result is an over-use error.

import pandas as pd

def stock_balance(received, used):
    for series in (received, used):
        if not isinstance(series, pd.Series):
            raise TypeError("two Series required")
        if not series.index.is_unique:
            raise ValueError("item labels must be unique")
        if any(not isinstance(label, str) or not label for label in series.index):
            raise ValueError("nonempty string item labels required")
        if str(series.dtype) != "int64" or bool((series < 0).any()):
            raise ValueError("nonnegative int64 quantities required")
    if set(received.index) != set(used.index):
        raise ValueError("both Series must describe the same items")
    # Reindex explicitly so the report follows the received order.
    aligned_used = used.reindex(received.index)
    result = received - aligned_used
    if bool((result < 0).any()):
        raise ValueError("usage exceeds received stock")
    result.name = "remaining"
    return result

received = pd.Series([10, 6], index=["pen", "book"], dtype="int64", name="received")
used = pd.Series([2, 3], index=["book", "pen"], dtype="int64", name="used")
result = stock_balance(received, used)
print(result.index.tolist(), result.tolist(), result.name)
print(received.tolist(), used.tolist())
try:
    stock_balance(received, pd.Series([1], index=["pen"], dtype="int64"))
except ValueError as error:
    print(type(error).__name__ + ": " + str(error))

# ✅ Expected output:
# ['pen', 'book'] [7, 4] remaining
# [10, 6] [2, 3]
# ValueError: both Series must describe the same items

Check reversed input order, a missing label, a duplicate label, an empty pair, a zero quantity, a negative input, an over-used item and an unsupported dtype. Comparing only result length would miss the central failure: pairing quantities with the wrong items.

Practice quiz

What does this program print? import pandas as pd s = pd.Series([7, 3], index=["b", "a"], dtype="int64") print(int(s.loc["a"]), int(s.iloc[0]))

  • 3 7
  • 7 3
  • 3 3
  • 7 7

Answer: 3 7. The label a and the first position refer to different observations.

What does this program print? import pandas as pd a = pd.Series([10, 6], index=["x", "y"], dtype="int64") b = pd.Series([2, 3], index=["y", "x"], dtype="int64") print(int((a-b).loc["x"]))

  • 8
  • 7
  • 4
  • 13

Answer: 7. x aligns with x, whose right-hand value is 3.

What does this program print? import pandas as pd s = pd.Series([4, 2], index=["a", "a"], dtype="int64") print(type(s.loc["a"]).__name__)

  • int
  • DataFrame
  • Series
  • Index

Answer: Series. Repeated labels return a Series for this label selection.

What does this program print? import pandas as pd s = pd.Series([4, 2], index=["a", "b"], dtype="int64") print("a" in s, 4 in s)

  • True True
  • False True
  • False False
  • True False

Answer: True False. Series membership tests index labels.

What does this program print? import pandas as pd s = pd.Series([4, None], dtype="Int64") print(int(s.count()), len(s))

  • 1 2
  • 2 2
  • 1 1
  • 2 1

Answer: 1 2. count excludes the missing value while length includes its row.

What does this program print? import pandas as pd s = pd.Series([4, 2], index=["a", "b"], dtype="int64") print(s.reindex(["b", "a"]).tolist())

  • [4, 2]
  • [2, 4]
  • ['b', 'a']
  • [2, 2]

Answer: [2, 4]. Reindex expresses a label order, carrying values with their labels.

Why can converting both inputs to NumPy before subtraction be wrong?

  • NumPy forbids subtraction
  • Every Series has duplicate labels
  • The conversion discards the label alignment contract
  • The conversion sorts all labels

Answer: The conversion discards the label alignment contract. Positional pairing can mismatch observations even when all numbers are valid.

What should stock_balance do when one input lacks an item label?

  • Silently invent zero usage
  • Drop the unmatched item
  • Pair the last available row
  • Reject the mismatched item set

Answer: Reject the mismatched item set. The brief explicitly treats missing items as invalid input.

Continue this course

Related lessons