Status
Done
TABLE OF CONTENT
1. Label-Based & Positional Access
df['series'].at→ Fast label-based scalar access (single value, like a dictionary).df['series'].iat→ Fast integer-position-based scalar access (likeatbut for positions).df['series'].loc→ Label-based indexing (slicing, single/multiple values).df['series'].iloc→ Integer-position-based indexing (slicing, single/multiple values).
Key Difference:
- Use
at/iatfor single values (optimized for speed). - Use
loc/ilocfor slices or multiple values.
2. Value Retrieval & Conversion
df['series'].get(key)→ Safe value access (returnsNone/default if key missing, likedict.get).df['series'].item()→ Extract the single value from a 1-element Series (raises error if size ≠ 1).df['series'].to_numpy()→ Convert Series to a NumPy array (preferred over.valuesin modern Pandas).df['series'].array→ Returns the underlying Pandas extension array (e.g.,IntegerArray,StringArray).
3. Data Removal & Iteration
df['series'].pop(key)→ Remove and return a value by label (modifies the Series in-place).df['series'].items()→ Iterate over (index, value) pairs (likedict.items).df['series'].iter()→ Alias for.items()(older Pandas versions).df['series'].keys()→ Alias for.index(returns index labels).
4. Advanced Selection
df['series'].xs(key)→ Cross-section (select value by label, similar to.locbut less common).
When to Use What?
- Need speed for single values? →
at(label) /iat(position). - Slicing or filtering? →
loc(label) /iloc(position). - Safe access with fallback? →
get(). - Convert to NumPy? →
to_numpy()(modern) or.values(legacy). - Iterate? →
items()oriter().
🔍 Access & Selection in Pandas Series (Titanic Dataset)
We will use the age column from the Titanic dataset to demonstrate all examples.
import pandas as pd
import seaborn as sns
# Load Titanic dataset
df = sns.load_dataset('titanic')
survived pclass sex age sibsp parch fare embarked class who adult_male deck embark_town alive alone
0 0 3 male 22.0 1 0 7.2500 S Third man True NaN Southampton no False
1 1 1 female 38.0 1 0 71.2833 C First woman False C Cherbourg yes False
2 1 3 female 26.0 0 0 7.9250 S Third woman False NaN Southampton yes True
3 1 1 female 35.0 1 0 53.1000 S First woman False C Southampton yes False
4 0 3 male 35.0 0 0 8.0500 S Third man True NaN Southampton no True
‣
1. Label-Based & Positional Access
‣
2. Value Retrieval & Conversion
‣
3. Data Removal & Iteration
‣
4. Advanced Selection
When to Use What? – Summary Table
Task | Use |
Access single label | at |
Access single position | iat |
Access multiple rows (labels) | loc |
Access multiple rows (positions) | iloc |
Safe access with fallback | get() |
Extract from 1-element Series | item() |
Convert to NumPy | to_numpy() |
Remove value | pop() |
Iterate over index-value pairs | items() / iter() |
Access index labels | keys() |
Cross-section selection (MultiIndex) | xs() |