惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
爱范儿
爱范儿
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
雷峰网
雷峰网
V
V2EX
博客园_首页
Engineering at Meta
Engineering at Meta
博客园 - 聂微东
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Apple Machine Learning Research
Apple Machine Learning Research
GbyAI
GbyAI
H
Help Net Security
A
About on SuperTechFans
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Blog — PlanetScale
Blog — PlanetScale
W
WeLiveSecurity
云风的 BLOG
云风的 BLOG
D
Docker
Security Archives - TechRepublic
Security Archives - TechRepublic
Help Net Security
Help Net Security
N
News and Events Feed by Topic
Simon Willison's Weblog
Simon Willison's Weblog
G
Google Developers Blog
A
Arctic Wolf
T
The Blog of Author Tim Ferriss
博客园 - 叶小钗
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Google DeepMind News
Google DeepMind News
博客园 - 三生石上(FineUI控件)
aimingoo的专栏
aimingoo的专栏
Hacker News: Ask HN
Hacker News: Ask HN
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 司徒正美
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy International News Feed
T
Troy Hunt's Blog
T
Tenable Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Recorded Future
Recorded Future
F
Fortinet All Blogs
D
DataBreaches.Net
B
Blog
T
Threat Research - Cisco Blogs
MyScale Blog
MyScale Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
The GitHub Blog
The GitHub Blog
Security Latest
Security Latest
M
MIT News - Artificial intelligence

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Filtering Rows and Selecting Columns (The Right Way)
Akhilesh · 2026-04-26 · via DEV Community

You know df["column"] selects a column.

You know df.head() shows the top rows.

But in real analysis, you need surgical precision. Give me rows 50 through 200 where salary is above the median and department is not Sales, and only show me the name, age, and salary columns.

That sentence is one Pandas expression when you know what you are doing. Three nested loops when you do not.

This post is about knowing what you are doing.


Two Ways to Select: loc and iloc

These are the two main selectors. They look similar but they think differently.

iloc thinks in positions. Row 0 is the first row. Column 2 is the third column. Pure integer indexing like NumPy.

loc thinks in labels. Use the actual row index value and the actual column name. More readable. More dangerous to confuse with iloc.

import pandas as pd

data = {
    "name":       ["Alex", "Priya", "Sam", "Jordan", "Lisa", "Ravi"],
    "age":        [25, 30, 22, 35, 28, 31],
    "salary":     [55000, 82000, 43000, 95000, 67000, 71000],
    "department": ["Engineering", "Marketing", "Engineering", "Sales", "Marketing", "Engineering"],
    "score":      [88, 92, 76, 85, 91, 79]
}

df = pd.DataFrame(data)
print(df)

Enter fullscreen mode Exit fullscreen mode

Output:

    name  age  salary   department  score
0   Alex   25   55000  Engineering     88
1  Priya   30   82000    Marketing     92
2    Sam   22   43000  Engineering     76
3 Jordan   35   95000        Sales     85
4   Lisa   28   67000    Marketing     91
5   Ravi   31   71000  Engineering     79

Enter fullscreen mode Exit fullscreen mode


iloc: Position-Based Selection

print(df.iloc[0])          # first row, all columns
print(df.iloc[2, 3])       # row index 2, column index 3 -> "Engineering"
print(df.iloc[1:4])        # rows 1, 2, 3 (4 is excluded)
print(df.iloc[:, 0:3])     # all rows, columns 0, 1, 2
print(df.iloc[[0, 3, 5]])  # rows 0, 3, and 5 specifically
print(df.iloc[-1])         # last row

Enter fullscreen mode Exit fullscreen mode

Output from df.iloc[2, 3]:

Engineering

Enter fullscreen mode Exit fullscreen mode

Output from df.iloc[[0, 3, 5]]:

     name  age  salary   department  score
0    Alex   25   55000  Engineering     88
3  Jordan   35   95000        Sales     85
5    Ravi   31   71000  Engineering     79

Enter fullscreen mode Exit fullscreen mode

iloc is straightforward. The confusion comes from people using it when they should use loc after filtering has shuffled the index.


loc: Label-Based Selection

print(df.loc[0])                          # row with index label 0
print(df.loc[0, "salary"])                # row 0, salary column -> 55000
print(df.loc[0:3, "name":"salary"])       # rows 0-3, columns name through salary
print(df.loc[[1, 4], ["name", "score"]]) # specific rows and columns by name

Enter fullscreen mode Exit fullscreen mode

Output from df.loc[0:3, "name":"salary"]:

     name  age  salary
0    Alex   25   55000
1   Priya   30   82000
2     Sam   22   43000
3  Jordan   35   95000

Enter fullscreen mode Exit fullscreen mode

Critical difference from iloc: loc[0:3] includes row 3. iloc[0:3] excludes row 3. loc slices are inclusive on both ends.


Why iloc Breaks After Filtering

This is the thing that catches everyone.

high_earners = df[df["salary"] > 65000]
print(high_earners)
print()
print(high_earners.iloc[0])  # first row of filtered df
print()
try:
    print(high_earners.loc[0])  # row with label 0
except KeyError as e:
    print(f"KeyError: {e}")

Enter fullscreen mode Exit fullscreen mode

Output:

    name  age  salary   department  score
1  Priya   30   82000    Marketing     92
3 Jordan   35   95000        Sales     85
4   Lisa   28   67000    Marketing     91
5   Ravi   31   71000  Engineering     79

name              Priya
age                  30
salary            82000
department    Marketing
score                92

KeyError: 0

Enter fullscreen mode Exit fullscreen mode

After filtering, the index labels are 1, 3, 4, 5. Row 0 no longer exists. loc[0] fails because there is no row labeled 0.

iloc[0] still works because it means "first row of this DataFrame, whatever its label is."

Use iloc when you want positional access after filtering. Use loc when you want to select by label and you know the labels.

Reset the index if you want to work with 0-based labels again:

high_earners_reset = high_earners.reset_index(drop=True)
print(high_earners_reset)

Enter fullscreen mode Exit fullscreen mode

Output:

    name  age  salary   department  score
0  Priya   30   82000    Marketing     92
1 Jordan   35   95000        Sales     85
2   Lisa   28   67000    Marketing     91
3   Ravi   31   71000  Engineering     79

Enter fullscreen mode Exit fullscreen mode

Labels now start at 0 again. drop=True removes the old index instead of saving it as a column.


Boolean Filtering: The Power Move

You already saw basic filtering in the Pandas post. This is the deep version.

Single condition:

seniors = df[df["age"] >= 30]
engineers = df[df["department"] == "Engineering"]
high_scorers = df[df["score"] > 85]

Enter fullscreen mode Exit fullscreen mode

Multiple conditions with AND:

eng_seniors = df[(df["department"] == "Engineering") & (df["age"] >= 28)]
print(eng_seniors[["name", "age", "department"]])

Enter fullscreen mode Exit fullscreen mode

Output:

  name  age   department
5  Ravi   31  Engineering

Enter fullscreen mode Exit fullscreen mode

Multiple conditions with OR:

marketing_or_high = df[(df["department"] == "Marketing") | (df["score"] > 90)]
print(marketing_or_high[["name", "department", "score"]])

Enter fullscreen mode Exit fullscreen mode

Output:

    name department  score
1  Priya  Marketing     92
4   Lisa  Marketing     91

Enter fullscreen mode Exit fullscreen mode

Negation with ~:

not_sales = df[~(df["department"] == "Sales")]
print(not_sales["department"].unique())

Enter fullscreen mode Exit fullscreen mode

Output:

['Engineering' 'Marketing']

Enter fullscreen mode Exit fullscreen mode

isin() for matching against a list:

selected_depts = df[df["department"].isin(["Engineering", "Marketing"])]
print(selected_depts["department"].value_counts())

Enter fullscreen mode Exit fullscreen mode

Output:

Engineering    3
Marketing      2

Enter fullscreen mode Exit fullscreen mode

between() for range checks:

mid_range = df[df["salary"].between(60000, 85000)]
print(mid_range[["name", "salary"]])

Enter fullscreen mode Exit fullscreen mode

Output:

   name  salary
1  Priya   82000
4   Lisa   67000
5   Ravi   71000

Enter fullscreen mode Exit fullscreen mode

str.contains() for partial string matching:

data2 = df.copy()
data2.loc[5, "name"] = "Ravi Kumar"

kumar = data2[data2["name"].str.contains("Kumar", case=False, na=False)]
print(kumar[["name", "department"]])

Enter fullscreen mode Exit fullscreen mode


Combining Selection and Filtering

The real pattern: filter rows first, then select only the columns you care about.

result = df.loc[df["salary"] > 65000, ["name", "salary", "department"]]
print(result)

Enter fullscreen mode Exit fullscreen mode

Output:

     name  salary   department
1   Priya   82000    Marketing
3  Jordan   95000        Sales
4    Lisa   67000    Marketing
5    Ravi   71000  Engineering

Enter fullscreen mode Exit fullscreen mode

df.loc[condition, columns] in one expression. Row selection and column selection together. This is the pattern you will use constantly.

Sort the result:

result_sorted = df.loc[df["salary"] > 65000, ["name", "salary", "department"]] \
                  .sort_values("salary", ascending=False)
print(result_sorted)

Enter fullscreen mode Exit fullscreen mode

Output:

     name  salary   department
3  Jordan   95000        Sales
1   Priya   82000    Marketing
5    Ravi   71000  Engineering
4    Lisa   67000    Marketing

Enter fullscreen mode Exit fullscreen mode

Method chaining. Filter, select columns, sort. All in one readable expression.


Modifying Values in Place

Filtering selects. loc can also assign.

df.loc[df["department"] == "Sales", "score"] += 5
print(df[df["department"] == "Sales"][["name", "department", "score"]])

Enter fullscreen mode Exit fullscreen mode

Output:

     name department  score
3  Jordan      Sales     90

Enter fullscreen mode Exit fullscreen mode

Jordan's score went from 85 to 90. Only the Sales rows were affected. Everyone else unchanged.

Never do this:

df[df["department"] == "Sales"]["score"] += 5   # wrong

Enter fullscreen mode Exit fullscreen mode

This is chained indexing. It creates a copy, modifies the copy, throws it away. The original DataFrame does not change. Pandas usually warns you with SettingWithCopyWarning. Use .loc for assignments. Always.


Quick Reference

df.iloc[row_number]                         # single row by position
df.iloc[start:end]                          # slice by position
df.iloc[row, col]                           # single value by position
df.loc[label]                               # single row by label
df.loc[start:end, col_name]                 # slice by label + column name
df.loc[bool_series, columns]                # filter + select columns
df[condition]                               # shorthand filter (rows only)
df[col_name]                                # single column
df[[col1, col2]]                            # multiple columns
df.query("salary > 60000 and age < 30")    # SQL-style string filter

Enter fullscreen mode Exit fullscreen mode

df.query() is worth knowing. It accepts a string expression and is sometimes more readable than boolean indexing for complex conditions.

result = df.query("salary > 60000 and age < 30")
print(result[["name", "age", "salary"]])

Enter fullscreen mode Exit fullscreen mode

Output:

   name  age  salary
4  Lisa   28   67000

Enter fullscreen mode Exit fullscreen mode


*args and **kwargs: Why They Matter Here

You have been calling Pandas methods with keyword arguments this whole series.

df.sort_values("salary", ascending=False)
df.fillna({"age": 0, "salary": df["salary"].median()})
df.read_csv("file.csv", sep=";", encoding="utf-8", nrows=1000)

Enter fullscreen mode Exit fullscreen mode

Those extra named arguments like ascending, encoding, nrows are kwargs. Keyword arguments. They have names and default values. You only pass them when you want to override the default.

*args and **kwargs are how Python functions accept a variable number of arguments. They are worth understanding deeply because you will use them when writing your own utility functions for data work.

def summarize(*columns, df=None, **agg_funcs):
    if df is None:
        return
    for col in columns:
        print(f"\n{col}:")
        for func_name, func in agg_funcs.items():
            print(f"  {func_name}: {func(df[col])}")

summarize("age", "salary", df=df, mean=lambda x: x.mean().round(1), maximum=max)

Enter fullscreen mode Exit fullscreen mode

Output:

age:
  mean: 28.5
  maximum: 35

salary:
  mean: 68833.3
  maximum: 95000

Enter fullscreen mode Exit fullscreen mode

*columns collects any number of positional arguments into a tuple. **agg_funcs collects any number of keyword arguments into a dictionary. This pattern shows up in utility functions, wrappers, and decorators. A dedicated deep-dive on *args and **kwargs is coming up after the core data tools posts.


Try This

Create filtering_practice.py.

Load the Titanic dataset (from the last post's practice).

Using only loc and iloc, do every one of these without loops:

Select the Name, Age, and Survived columns for the first 10 passengers using iloc.

Find all female passengers who survived. Show only Name, Age, and Fare.

Find passengers who paid more than 50 for their ticket and were in first class. How many are there?

Use str.contains to find passengers whose name contains "Mrs." Show their names and ages.

Select the last 5 rows of the dataset using iloc negative indexing.

Use df.query() to find passengers younger than 18 who survived. Compare the result to the boolean indexing version. They should be identical.

For each result, chain a .sort_values() to sort by age descending.


What's Next

You can select any slice of your data now. The next step is finding patterns across groups. Average salary per department. Count of survivors per passenger class. Maximum score per category. That is groupby, and it is one of the most powerful tools in data analysis.