Concept Flow - Series indexing and selection
Create Series with index
Choose index or slice
Check if index exists
Return value
Use selected data
Start with a Series, pick an index or slice, check if it exists, then return the value or error.
import pandas as pd s = pd.Series([10, 20, 30], index=['a', 'b', 'c']) val = s['b'] slice_s = s['a':'b']
| Step | Action | Index/Label Accessed | Result | Notes |
|---|---|---|---|---|
| 1 | Create Series | ['a', 'b', 'c'] | [10, 20, 30] | Series created with labels a,b,c |
| 2 | Select single value | 'b' | 20 | Label 'b' exists, returns 20 |
| 3 | Select slice | 'a':'b' | Series with labels 'a' and 'b' | Slice includes 'a' and 'b' inclusive |
| 4 | Attempt invalid index | 'd' | KeyError | Label 'd' does not exist, error raised |
| Variable | Start | After Step 2 | After Step 3 | After Step 4 |
|---|---|---|---|---|
| s | Series(['a':10, 'b':20, 'c':30]) | Same | Same | Same |
| val | Undefined | 20 | 20 | 20 |
| slice_s | Undefined | Undefined | Series(['a':10, 'b':20]) | Series(['a':10, 'b':20]) |
Series indexing and selection: - Use s[label] to get single value by label - Use s[start_label:end_label] to slice by labels (inclusive) - Accessing missing label raises KeyError - Index labels can be strings or numbers - Label slicing includes the end label