In pandas 3.0, pay = emp.set_index('name')['salary'] makes pay[0] raise KeyError where pandas 2.x returned the first salary; what changed, and what still behaves positionally?
answer
- the positional fallback is gone
- deprecated in 2.1
- integer slices kept their meaning
- a write can append a row
basics
~20 sIn pandas 3.0, Series [] and []= treat an integer key as a label, never a position, so pay[0] looks for a name 0 and raises KeyError. Use pay.iloc[0]. Integer slices such as pay[0:2] stay positional.
solid answer
~40 spandas 2.x fell back to positions when a Series index was not integer-typed: on a name index `pay[0]` returned the first salary, with a `FutureWarning` from 2.1 on. In pandas 3.0, `Series.__getitem__` and `Series.__setitem__` always treat integer keys as labels, matching DataFrame, so `pay[0]`, `pay[-1]` and `pay[[0, 1]]` raise `KeyError`. The write side is the dangerous one: `pay[0] = 1` no longer overwrites the first salary, it **appends** a row labelled `0`, silently. Integer **slices** did not change: `pay[0:2]` still returns the first two rows. On an integer index nothing changed either, because integer keys were already labels there. The fix is mechanical: `iloc` for positions, `loc` for labels, and run the test suite on the last 2.x with `FutureWarning` turned into an error before upgrading.
code
python · 23 linesimport pandas as pd
emp = pd.DataFrame(
{"name": ["ana", "ben", "cho"], "salary": [52000, 81000, 77000]},
index=pd.Index([1042, 1007, 1311], name="emp_id"),
)
pay = emp.set_index("name")["salary"] # index of names, not integers
for key in (0, -1):
try:
pay[key]
except KeyError as err:
print("KeyError:", err)
print(repr(pay.iloc[0])) # position: the explicit way
print(pay[0:2].index.tolist()) # integer slice: still positional
ids = emp["salary"] # integer ID index
print(repr(ids[1007])) # integer key on an integer index: a label
pay2 = pay.copy()
pay2[0] = 1 # a label write: appends a row labelled 0
print(pay2.index.tolist(), pay2.iloc[0])go deeper
Recall that in pandas 3.0 an integer in Series brackets is a label, so use iloc for the first or last value.
Explain which Series were affected (non-integer indexes), why integer-indexed ones were not, and why integer slices still mean positions.
Show you can de-risk an upgrade: surface the 2.x FutureWarnings as errors, rewrite reads by intent, and audit integer-key writes that now enlarge the Series instead of overwriting.
Frame the migration as a team rule: explicit loc and iloc in all new code, a CI run with deprecation warnings as errors on the last 2.x, and a review check for bare integer keys on Series.
## What pandas 2.x did A `Series` can be indexed with plain square brackets, `s[key]`. Before pandas 3.0 the meaning of an **integer** key depended on the index: - On an **integer index** (for example employee IDs), an integer key was a **label**: `ids[1007]` returned employee 1007 and `ids[0]` raised `KeyError`. - On a **non-integer index** (names, dates, strings), pandas **fell back to position**: `pay[0]` returned the first value and `pay[-1]` the last. So the same expression meant different things depending on data the reader could not see. pandas 2.1 deprecated the fallback, and every such call printed `FutureWarning: Series.__getitem__ treating keys as positions is deprecated` (and the matching `Series.__setitem__` message for writes), pointing to `ser.iloc[pos]`. ## What pandas 3.0 does In pandas 3.0 the deprecation was enforced: `Series.__getitem__` and `Series.__setitem__` **always treat integer keys as labels, never as positions**, "consistent with DataFrame behavior", as the 3.0 release notes put it. On a Series indexed by employee names: | Expression | pandas 2.x (2.1 and later) | pandas 3.0 | |---|---|---| | `pay[0]` | first salary, with `FutureWarning` | `KeyError: 0` | | `pay[-1]` | last salary, with `FutureWarning` | `KeyError: -1` | | `pay[[0, 1]]` | first two salaries, with `FutureWarning` | `KeyError` (none of the labels found) | | `pay[0] = 1` | overwrites the first salary, with `FutureWarning` | appends a new row labelled `0` | | `pay.get(0)` | first salary, with `FutureWarning` | `None` (label 0 absent) | | `pay[0:2]` | first two rows | first two rows (unchanged) | | `pay.iloc[0]` | first salary | first salary | The same applies to any index that is not integer-typed, including a `DatetimeIndex`: on a daily series, `d[0]` now raises `KeyError` while `d["2026-01-02"]` and `d.iloc[0]` work. ## Integer slices are still positional Slices were handled separately. A deprecation of positional integer slicing on an integer index was started and then reverted in pandas 1.5.3, so `s[0:2]` remains **positional and half-open** on every index type, matching `df[0:2]` on a DataFrame. pandas 3.0 went further in the same direction: an integer slice on a **float-dtype** index is now positional too. The asymmetry is the trap: `pay[0]` is a label lookup, `pay[0:2]` is a positional slice. Writing `pay.iloc[0:2]` removes the doubt. ## The silent write Reads fail loudly in 3.0; writes do not. Assigning to a missing label is **setting with enlargement**, so `pay[0] = 1` adds a fourth row with label `0` and leaves `ana`'s salary untouched. Code that used to patch the first value now grows the Series, and the error shows up later as a wrong row count, a mixed-type index, or a join that suddenly matches nothing. Setting with enlargement in general is part of assigning values; what matters here is that an integer key on a non-integer index now takes that path. ## Integer indexes did not change If the index already held integers, integer keys were labels in 2.x as well, so `ids[1007]` and the `KeyError` from `ids[0]` behave identically in both versions. The upgrade risk sits in Series indexed by names, codes, dates or strings, which is where the 2.x fallback used to answer. ## Why pandas made the change - **One rule for both objects.** `DataFrame.__getitem__` never fell back to positions for an integer key; aligning Series removes a difference that surprised people moving between the two. - **Data-independent meaning.** In 2.x, `s[0]` changed meaning when an upstream step changed the index dtype, for example after `set_index` or `reset_index`; in pandas 3.0 the expression means the same thing on every index. - **Explicit accessors exist.** `iloc` and `iat` already express positions, so the fallback added ambiguity without adding capability. ## Migrating code 1. **Find the call sites on 2.x first.** Run the tests on the last 2.x release with the warning promoted to an error, for example `pytest -W error::FutureWarning`; every positional fallback then fails at its own line. 2. **Rewrite by intent.** A position becomes `s.iloc[0]` or `s.iat[0]`; a label becomes `s.loc[label]` or `s.at[label]`. 3. **Audit writes separately.** Search for `s[<int>] =` on Series that are not integer-indexed, because in 3.0 they enlarge instead of raising. 4. **Prefer explicit accessors in new code** so the meaning never depends on the index dtype.
- Why do integer slices on a Series remain positional when integer keys became labels?Slicing was handled on its own track: a deprecation of positional integer slicing on an integer index was reverted in pandas 1.5.3, so `s[0:2]` stays positional and half-open, matching `df[0:2]`. In pandas 3.0 an integer slice on a float-dtype index became positional as well. Write `s.iloc[0:2]` or `s.loc[a:b]` so the meaning does not depend on the key's type.
- How do you find every affected call site in a 2.x codebase before upgrading to pandas 3.0?Run the test suite on the last 2.x release with the deprecation promoted to an error, for example `pytest -W error::FutureWarning`. Each positional fallback raises at its own line with 'Series.__getitem__ treating keys as positions is deprecated' or the `__setitem__` variant, and the message names the replacement, `ser.iloc[pos]`.
- What does pay.get(0) return in pandas 3.0 on a Series indexed by names?`None`, or the default you pass. `Series.get` looks the key up as a label like `[]` does, and returns the default instead of raising when the label is absent. On 2.x it fell back to position with a `FutureWarning` and returned the first salary, so a silent `None` is another symptom of code that relied on the fallback.
- In pandas 3.0, integer keys no longer work on a Series indexed by integer IDs.
- In pandas 3.0, pay[0:2] also raises KeyError on a name index.
- In pandas 3.0, pay[0] = value still overwrites the first element.
- The pandas 3.0 change mostly affects Series with an integer index.
- pay[-1] still returns the last element in pandas 3.0.
Assumes pandas 3.0: 2.x let Series [] and []= fall back to positions on a non-integer index (FutureWarning since 2.1); 3.0 always reads integer keys as labels.