Selecting and Filtering
Pick the rows and columns you want using labels, positions and conditions.
Syntax
df[df['col'] > value]Two main accessors select data:
.loc[rows, cols]selects by label..iloc[rows, cols]selects by integer position.
Boolean filtering
A condition inside the brackets keeps only matching rows. Combine conditions with & (and) and | (or), wrapping each in parentheses.
Example
import pandas as pd
df = pd.DataFrame({
'name': ['Ann', 'Bob', 'Cara', 'Dan'],
'age': [34, 29, 41, 22],
'city': ['Paris', 'Rome', 'Oslo', 'Rome'],
})
print(df[df['age'] > 30]) # rows where age > 30
print(df.loc[df['city'] == 'Rome', 'name']) # names in Rome
print(df.iloc[0:2]) # first two rowsWhen to use it
- An analyst uses boolean filtering to extract all rows where a customer's purchase amount exceeds 500 dollars before computing segment averages.
- An ML engineer selects only numeric feature columns with df.select_dtypes('number') to pass directly to a scaler without manual column listing.
- A data scientist uses .loc with a list of column names to reorder and subset a DataFrame to the exact feature set a model expects.
More examples
Select columns and rows by label
Shows the three most common selection patterns: single column, multiple columns, and a row by its label index.
import pandas as pd
df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6], 'c': [7,8,9]})
print(df['a']) # single column -> Series
print(df[['a', 'c']]) # multiple columns -> DataFrame
print(df.loc[1]) # row by labelBoolean condition filtering
Filters rows using a boolean condition and combines two conditions with & to find high-value US customers.
import pandas as pd
df = pd.read_csv('customers.csv')
high_value = df[df['purchase_amount'] > 500]
vip = df[(df['purchase_amount'] > 500) & (df['country'] == 'US')]
print(vip.shape)iloc for position-based access
Uses iloc for purely integer-position access, useful when column names are unknown or when slicing by numeric position like in train/test splits.
import pandas as pd
import numpy as np
df = pd.DataFrame(np.arange(20).reshape(4, 5),
columns=list('ABCDE'))
print(df.iloc[0, :]) # first row, all columns
print(df.iloc[:2, 2:]) # top-left block by position
Discussion