Indexing, Filtering, and Boolean Masks
Select rows and columns with loc, iloc, and boolean conditions.
loc vs iloc
loc selects by label; iloc selects by integer position. Never mix them up.
import pandas as pd
df = pd.DataFrame({"a":[1,2,3],"b":[4,5,6]}, index=["x","y","z"])
print(df.loc["y"]) # row with label y
print(df.iloc[1]) # row at position 1 (same row)
print(df.loc["x":"y"]) # rows x to y inclusiveBoolean Mask Filtering
Create a boolean Series and use it to select rows. This is the pandas equivalent of NumPy boolean indexing.
import pandas as pd
df = pd.DataFrame({"name":["Alice","Bob","Carol"],"age":[30,17,25]})
adults = df[df["age"] >= 18]
print(adults)
# Alice 30
# Carol 25All lessons in this course
- Series and DataFrame Fundamentals
- Indexing, Filtering, and Boolean Masks
- GroupBy, Aggregation, and Pivot Tables
- Merging, Joining, and Data Cleaning