In pandas, what do emp['salary'], emp[['salary']] and emp[0:2] return, and why does emp[0] raise KeyError?
answer
- one bracket pair versus two
- Series or one-column DataFrame
- a slice means rows
- a scalar means a column
basics
~20 sOn a DataFrame, [] with one name returns that column as a Series, a list returns a DataFrame, and an integer slice returns rows by position. emp[0] raises KeyError because a scalar key looks for a column named 0.
solid answer
~40 s`DataFrame.__getitem__` decides by the type of the key. A single label, `emp['salary']`, returns that column as a `Series` named `salary`; a list, even a one-element list, `emp[['salary']]`, returns a `DataFrame` with those columns in the order listed. A slice is the exception: `emp[0:2]` selects **rows**, by position and half-open, even when the index holds integer IDs. So `emp[0]` is a lookup for a column named `0` and raises `KeyError: 0` when there is none. A tuple such as `emp['name', 'salary']` is also one key, so it raises `KeyError` unless the columns are a MultiIndex; two columns need the inner list. On a Series, by contrast, `s[label]` returns the value stored under that label. When you mean rows, write `loc` or `iloc` so nobody has to infer intent from the key's type.
code
python · 22 linesimport pandas as pd
emp = pd.DataFrame(
{"name": ["Ana", "Ben", "Cho", "Dev", "Eli"],
"dept": ["ops", "eng", "eng", "hr", "ops"],
"salary": [52000, 81000, 77000, 60000, 49000]},
index=pd.Index([1042, 1007, 1311, 1099, 1500], name="emp_id"),
)
col = emp["salary"] # one label -> Series
frame = emp[["salary"]] # a list -> DataFrame
rows = emp[0:2] # a slice -> rows, by position
print(type(col).__name__, col.shape, col.name)
print(type(frame).__name__, frame.shape, list(frame.columns))
print(type(rows).__name__, rows.index.tolist())
for key in (0, ("name", "salary")):
try:
emp[key]
except KeyError as err:
print("KeyError:", err)go deeper
Recall the four shapes: one name gives a Series, a list gives a DataFrame, a slice gives rows, a scalar that is not a column name gives KeyError. Say which brackets you need for two columns.
Explain that DataFrame [] dispatches on the key's type, why a tuple is one key, and why emp[0:2] works on an ID index while emp[0] fails.
Show that you keep [] for columns and use loc or iloc for rows, so code states its axis and never stacks brackets that turn into chained assignment on a write.
Treat it as a readability convention for a team: [] for column projection only, explicit accessors for rows, and a linter or review rule against stacked bracket selections.
## [] is a dispatcher, not one rule Square brackets on a pandas object call `__getitem__`, and on a `DataFrame` that method looks at the **type of the key** before deciding which axis to index. The user guide describes its main job as "selecting out lower-dimensional slices": a column out of a frame, a value out of a Series. Everything else is a convenience layered on top. | Key passed to `emp[...]` | Axis | Returns | |---|---|---| | one column label, `"salary"` | columns | a `Series` named `salary` | | a list of labels, `["salary"]` or `["salary", "name"]` | columns | a `DataFrame`, columns in the listed order | | an integer slice, `0:2` | rows, by position | a `DataFrame` of the first two rows | | a boolean Series of row length | rows | the rows where it is `True` (covered with boolean masks) | | a callable | either | whatever the callable's result selects | On a `Series`, `s[label]` returns a scalar, because there is only one axis left to index. ## Series versus one-column DataFrame `emp["salary"]` and `emp[["salary"]]` hold the same numbers but are different objects: - **`emp["salary"]`** is a one-dimensional `Series` with shape `(5,)`; its column name becomes the Series' `name`. It has no `.columns` attribute. - **`emp[["salary"]]`** is a two-dimensional `DataFrame` with shape `(5, 1)`; it keeps a header, so `.columns`, `shape[1]` and other DataFrame-only behaviour still work. - A list may also **reorder**: `emp[["salary", "name"]]` returns the two columns in that order. The difference matters when the result goes to code that expects two dimensions, or when you print or export it and expect a header row. A related trap sits on the other axis: a single row pulled out with `emp.loc[1007]` is also a Series, and because one Series holds one dtype, a row mixing text and integers comes back as `object`. ## Slices select rows The one key type that does *not* select columns is a slice. `emp[0:2]` returns the first two **rows**, by position and half-open, and it does so on an index of employee IDs too, where `0` and `2` are not labels at all. That is why the same frame answers `emp[0:2]` but raises on `emp[0]`: the scalar goes down the column path, and there is no column named `0`. Label slices are tried when the slice bounds are not integers, so on a date index `df["2026-01-01":"2026-01-31"]` selects a range of rows by label. Because the rule depends on the key type, a reader has to work out which case applies; `emp.iloc[0:2]` and `emp.loc[1042:1007]` say it outright. ## The tuple trap and missing columns Python turns `emp["name", "salary"]` into `emp[("name", "salary")]`, **one** key that happens to be a tuple. On flat columns pandas looks for a single column labelled `("name", "salary")` and raises `KeyError: ('name', 'salary')`. On MultiIndex columns the same tuple is a legitimate key across column levels, which is why pandas cannot simply guess what you meant. The fix is the inner list: `emp[["name", "salary"]]`. A list that names a missing column fails as a whole: `emp[["name", "bonus"]]` raises `KeyError: "['bonus'] not in index"`. pandas does not drop the unknown name and return the rest. ## [] on a Series A Series has one axis, so `s[label]` is a label lookup that returns a scalar, and `s[[l1, l2]]` returns a smaller Series. Integer keys on a Series whose index is not integer-typed are a separate trap with their own history. When the meaning matters, use `s.loc[...]` for labels and `s.iloc[...]` for positions. ## Mistakes interviewers listen for - Expecting `emp[0]` to return the first row; it is a column lookup. - Writing `emp["name", "salary"]` for two columns and reading the `KeyError` as a missing column rather than a missing inner list. - Passing `emp["salary"]` where the next step needs a frame with a header, then debugging a `.columns` attribute error. - Reading `emp[0:2]` as a label range on an ID index; it is positional. ## When to reach for loc and iloc instead 1. **Columns by name** — `emp["salary"]` and `emp[["name", "salary"]]` are idiomatic and widely read. 2. **Rows** — prefer `emp.iloc[0:2]` or `emp.loc[1042:1007]` to `emp[0:2]`, so the axis and coordinate system are visible. 3. **Rows and columns together** — use one accessor with two selectors, `emp.loc[1007, "salary"]`, rather than stacking brackets such as `emp["salary"][1007]`; one call is clearer, and stacked brackets become chained assignment the moment you try to write through them.
- When would you deliberately write emp[['salary']] instead of emp['salary']?When the next step needs two dimensions: code that reads `.columns` or `shape[1]`, a function that expects a DataFrame argument, or an export where the header row must survive. `emp[['salary']]` keeps a one-column DataFrame with its column name; `emp['salary']` is a 1-D Series whose column name moved into `.name`.
- On a frame indexed by integer employee IDs, does emp[0:2] select by label or by position?By position. An integer slice in DataFrame `[]` is positional and half-open even when the index holds integers, so it returns the first two stored rows whatever their IDs. For a label range write `emp.loc[1042:1007]`, which includes both endpoints; for a positional range, `emp.iloc[0:2]` says so explicitly.
- emp['salary'] and emp[['salary']] both return a Series.
- emp[0] returns the first row of the DataFrame.
- emp['name', 'salary'] selects the name and salary columns.
- emp[0:2] selects the first two columns.
- A missing name in emp[['name', 'bonus']] is skipped and the rest returned.