💡 Understanding Accessors: `.loc` vs `.iloc`
Once your data is loaded into a Pandas DataFrame, the most frequent operation is selecting specific subsets. Pandas provides two powerful indexers:
1. .iloc[] (Integer Location): Indexes purely by integer position (similar to standard Python slicing where indices start at `0`).
2. .loc[] (Location): Indexes by label name (rows and columns specified by their index labels or column headers).
1. Selecting Single and Multiple Columns
Extracting individual columns as Series or multiple columns as a sub-DataFrame from a dataset.
Python (select_columns.py)
import pandas as pd
def select_cols():
data = {
'Product': ['Laptop', 'Mouse', 'Keyboard', 'Monitor'],
'Category': ['Electronics', 'Accessories', 'Accessories', 'Electronics'],
'Price': [1200, 25, 75, 300]
}
df = pd.DataFrame(data)
print("--- Single Column (Series) ---")
print(df['Product'])
print("\n--- Multiple Columns (DataFrame) ---")
print(df[['Product', 'Price']])
select_cols()
Output:
--- Single Column (Series) ---
0 Laptop
1 Mouse
2 Keyboard
3 Monitor
Name: Product, dtype: object
--- Multiple Columns (DataFrame) ---
Product Price
0 Laptop 1200
1 Mouse 25
2 Keyboard 75
3 Monitor 300
2. Position-Based Selection Using `.iloc[]`
Selecting rows and columns using strict integer offsets, perfect for slicing rows by sequence.
Python (iloc_selection.py)
import pandas as pd
def iloc_demo():
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'Diana'],
'Department': ['HR', 'IT', 'Finance', 'Engineering'],
'Salary': [60000, 85000, 90000, 110000]
}
df = pd.DataFrame(data, index=['A', 'B', 'C', 'D'])
# Select first row by integer position 0
print("Row at index position 0:")
print(df.iloc[0])
# Select rows from index 1 to 3, and columns 0 and 2
print("\nSliced sub-matrix (.iloc[1:3, [0, 2]]):")
print(df.iloc[1:3, [0, 2]])
iloc_demo()
Output:
Row at index position 0:
Name Alice
Department HR
Salary 60000
Name: A, dtype: object
Sliced sub-matrix (.iloc[1:3, [0, 2]]):
Name Salary
B Bob 85000
C Charlie 90000
3. Label-Based Selection Using `.loc[]`
Selecting rows and columns by their custom index labels and column header names.
Python (loc_selection.py)
import pandas as pd
def loc_demo():
data = {
'Score': [88, 92, 79, 95],
'Grade': ['B', 'A', 'C', 'A+']
}
df = pd.DataFrame(data, index=['John', 'Emma', 'Liam', 'Olivia'])
# Select specific row label 'Emma' and columns
print("Record for 'Emma':")
print(df.loc['Emma'])
# Select slice of rows from 'John' to 'Liam' and column 'Score'
print("\nScore slice from 'John' to 'Liam':")
print(df.loc['John':'Liam', ['Score']])
loc_demo()
Output:
Record for 'Emma':
Score 92
Grade A
Name: Emma, dtype: object
Score slice from 'John' to 'Liam':
Score
John 88
Emma 92
Liam 79
4. Conditional Boolean Filtering (Single Condition)
Filtering rows where a column matches a boolean threshold (e.g., extracting orders greater than $500).
Python (boolean_filter.py)
import pandas as pd
def filter_orders():
data = {
'OrderID': [101, 102, 103, 104, 105],
'Amount_USD': [150, 620, 430, 890, 210]
}
df = pd.DataFrame(data)
# Filter orders greater than $400
high_value = df[df['Amount_USD'] > 400]
print(high_value.to_string(index=False))
filter_orders()
Output:
OrderID Amount_USD
102 620
103 430
104 890
5. Multi-Condition Filtering (`&` and `|` Operators)
Combining multiple boolean conditions using bitwise operators (`&` for AND, `|` for OR) with mandatory parentheses.
Python (multi_condition.py)
import pandas as pd
def multi_filter():
data = {
'City': ['New York', 'London', 'Paris', 'New York', 'London'],
'Temperature': [72, 55, 68, 85, 60],
'Humidity': [40, 80, 50, 30, 85]
}
df = pd.DataFrame(data)
# City is New York AND Temperature > 75
filtered = df[(df['City'] == 'New York') & (df['Temperature'] > 75)]
print(filtered.to_string(index=False))
multi_filter()
Output:
City Temperature Humidity
New York 85 30
6. Using `.isin()` for Membership Filtering
Checking whether column values exist within a specified list of targets, replacing cumbersome `|` chains.
Python (isin_filter.py)
import pandas as pd
def isin_demo():
data = {
'Employee': ['Alice', 'Bob', 'Charlie', 'Diana', 'Evan'],
'Office': ['Tokyo', 'London', 'New York', 'Berlin', 'Tokyo']
}
df = pd.DataFrame(data)
# Find employees in Tokyo or Berlin
selected = df[df['Office'].isin(['Tokyo', 'Berlin'])]
print(selected.to_string(index=False))
isin_demo()
Output:
Employee Office
Alice Tokyo
Diana Berlin
Evan Tokyo
7. Assigning New Columns & Modifying Values
Adding a brand new calculated column to a DataFrame and updating specific rows using `.loc[]`.
Python (assign_columns.py)
import pandas as pd
def assign_demo():
data = {
'Item': ['Book', 'Pen', 'Bag'],
'Price': [20, 2, 50],
'Quantity': [3, 10, 2]
}
df = pd.DataFrame(data)
# Create new column Total Cost
df['Total_Cost'] = df['Price'] * df['Quantity']
# Update price for 'Pen' using .loc
df.loc[df['Item'] == 'Pen', 'Price'] = 2.50
print(df.to_string(index=False))
assign_demo()
Output:
Item Price Quantity Total_Cost
Book 20.0 3 60
Pen 2.5 10 20
Bag 50.0 2 100
8. Conditional Assignment with `np.where()`
Assigning values conditionally (like an Excel IF statement) across an entire column using NumPy's vectorized `where` method.
Python (np_where_assign.py)
import pandas as pd
import numpy as np
def conditional_assignment():
data = {
'Student': ['Sam', 'Grace', 'Alex', 'Taylor'],
'Score': [85, 42, 91, 58]
}
df = pd.DataFrame(data)
# If Score >= 60 -> 'Pass', Else -> 'Fail'
df['Status'] = np.where(df['Score'] >= 60, 'Pass', 'Fail')
print(df.to_string(index=False))
conditional_assignment()
Output:
Student Score Status
Sam 85 Pass
Grace 42 Fail
Alex 91 Pass
Taylor 58 Fail
9. Setting and Resetting Index Labels
Promoting an existing column to become the DataFrame index (`.set_index()`) and resetting it back to default integers (`.reset_index()`).
Python (set_reset_index.py)
import pandas as pd
def index_manipulation():
data = {
'Country': ['USA', 'UK', 'Canada'],
'Capital': ['Washington DC', 'London', 'Ottawa']
}
df = pd.DataFrame(data)
# Set 'Country' as index
df_indexed = df.set_index('Country')
print("--- Indexed DataFrame ---")
print(df_indexed)
# Reset index back to normal
df_reset = df_indexed.reset_index()
print("\n--- Reset DataFrame ---")
print(df_reset)
index_manipulation()
Output:
--- Indexed DataFrame ---
Capital
Country
USA Washington DC
UK London
Canada Ottawa
--- Reset DataFrame ---
Country Capital
0 USA Washington DC
1 UK London
2 Canada Ottawa
10. Using `.query()` for SQL-Like Readable Filtering
Filtering DataFrames using SQL-like syntax expressions via Pandas `.query()` method for cleaner readability.
Python (query_method.py)
import pandas as pd
def query_demo():
data = {
'Department': ['Sales', 'IT', 'Sales', 'HR', 'IT'],
'Experience_Years': [2, 5, 8, 1, 6],
'Salary': [50000, 95000, 110000, 45000, 105000]
}
df = pd.DataFrame(data)
# Query: Experience >= 5 AND Salary > 90000
senior_high_earners = df.query("Experience_Years >= 5 and Salary > 90000")
print(senior_high_earners.to_string(index=False))
query_demo()
Output:
Department Experience_Years Salary
IT 5 95000
Sales 8 110000
IT 6 105000