How to Select Rows in pandas DataFrame Easily
To select a row in pandas, use
loc for label-based selection or iloc for position-based selection. You can also select rows by condition using boolean indexing with DataFrame[condition].Syntax
Here are the main ways to select rows in pandas:
df.loc[label]: Select row by index label.df.iloc[position]: Select row by integer position.df[condition]: Select rows where condition is True.
python
df.loc[row_label] df.iloc[row_position] df[condition]
Example
This example shows how to select rows by label, position, and condition.
python
import pandas as pd data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]} df = pd.DataFrame(data, index=['a', 'b', 'c']) # Select row by label 'b' row_label = df.loc['b'] # Select row by position 2 (third row) row_position = df.iloc[2] # Select rows where Age > 28 rows_condition = df[df['Age'] > 28] print('Row by label b:\n', row_label) print('\nRow by position 2:\n', row_position) print('\nRows where Age > 28:\n', rows_condition)
Output
Row by label b:
Name Bob
Age 30
Name: b, dtype: object
Row by position 2:
Name Charlie
Age 35
Name: c, dtype: object
Rows where Age > 28:
Name Age
b Bob 30
c Charlie 35
Common Pitfalls
Common mistakes when selecting rows include:
- Using
locwith integer positions instead of labels. - Using
ilocwith labels instead of positions. - Forgetting that
df[condition]returns multiple rows, not a single row.
Always check if your DataFrame index is default integers or custom labels to choose loc or iloc correctly.
python
import pandas as pd data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]} df = pd.DataFrame(data, index=['x', 'y']) # Wrong: using iloc with label 'x' (raises error) # df.iloc['x'] # This will cause an error # Correct: use loc for label row = df.loc['x'] print(row)
Output
Name Alice
Age 25
Name: x, dtype: object
Quick Reference
| Method | Description | Example |
|---|---|---|
| loc | Select row by index label | df.loc['row_label'] |
| iloc | Select row by integer position | df.iloc[0] |
| Boolean Indexing | Select rows by condition | df[df['Age'] > 30] |
Key Takeaways
Use df.loc[label] to select rows by index label.
Use df.iloc[position] to select rows by integer position.
Use boolean conditions inside df[...] to select rows matching criteria.
Check your DataFrame index type to choose loc or iloc correctly.
Boolean indexing returns all rows matching the condition, not just one.