-->
Written by: Marlon Colca
Posted on 13 May 2025 - 3 months ago
python pandas analytics
Master the art of selecting rows and columns using Pandas. Learn `loc`, `iloc`, conditions, and slicing techniques.
Once your data is loaded and clean, the next step is to zoom in on what matters — rows, columns, and specific conditions.
In this post, we’ll cover:
✅ Selecting specific columns
✅ Filtering rows with conditions
✅ Using .loc[]
and .iloc[]
✅ Combining multiple filters
✅ Slicing data like a pro
Let’s slice and dice!
import pandas as pd
df = pd.read_csv("prices_sample.csv")
Just want one column?
df["price"]
Multiple columns?
df[["product_name", "price"]]
Let’s say you want all products that cost more than 5:
df[df["price"] > 5]
Now products that are in stock:
df[df["in_stock"] == True]
Or products not in stock and price below 4:
df[(df["in_stock"] == False) & (df["price"] < 4)]
.loc[]
and .iloc[]
.loc[]
is label-based.
.iloc[]
is index-based.
Example with .loc[]
:
# First row, all columns
df.loc[0]
# First 3 rows, specific columns
df.loc[0:2, ["product_name", "price"]]
Example with .iloc[]
:
# First row
df.iloc[0]
# First 5 rows and first 3 columns
df.iloc[0:5, 0:3]
Let’s say you want the top 10 most expensive products:
df.sort_values("price", ascending=False).head(10)
Or the 5 cheapest in stock:
df[df["in_stock"] == True].sort_values("price").head(5)
.query()
for readable filtersYou can also use .query()
to write conditions in a cleaner way:
df.query("in_stock == True and price < 5")
Much easier to read and chain when things get complex.
Filtering and selecting is one of the most common things you’ll do in Pandas.
[]
, .loc[]
, .iloc[]
to select rows and columns.query()
for clarity in complex logic.sort_values()
and .head()
to get top/bottom listsIn Part 5, we’ll group and summarize data:
➡️ averages per category, counts per brand, pivot tables and more.
Don’t miss it — things get real 🔥
Learn how to group, aggregate, and pivot your data using Pandas. Master `groupby`, `agg`, and `pivot_table` with real examples.