Pandas技术疑问:使用iloc检索数据为何与输入索引不匹配?
iloc Sometimes Doesn't Match Your Input Indices Great question! Let's clear up the confusion between loc and iloc—this is a super common pitfall when working with pandas DataFrames.
The Core Difference: Label vs. Position Indexing
The key issue here boils down to what each method uses to fetch rows:
locis label-based: it references the actual index labels (the values in your DataFrame'sindexcolumn, like 1, 2, 50, 9350 in your example).ilocis position-based: it looks at the physical order of rows in the DataFrame, starting from 0 (so the first row is position 0, second is 1, and so on).
Why the Mismatch Occurs
When you run data.loc[data.contributor_message == '...'].index, you're collecting label indices, not physical row positions. If your DataFrame uses the default continuous integer index (0, 1, 2, ...), labels and positions line up perfectly—so iloc[[1,2,50]] works as expected. But if your index has been modified (e.g., you deleted rows, filtered the DataFrame without resetting the index, or set a custom non-continuous index), the labels no longer match the physical positions.
For example:
Suppose you deleted row 3 from your DataFrame. Your index might now look like [0,1,2,4,5,...]. If you use loc to get label 4, that’s the 4th row (physical position 3), but iloc[4] would grab the 5th row (physical position 4, label 5)—two completely different rows!
The Fix: Use the Right Tool for the Job
Since you’re working with label indices from loc, stick with loc to retrieve the matching rows:
# Get the matching label indices matching_labels = data.loc[data.contributor_message == 'I support this proposal because...'].index # Retrieve the rows using loc matching_rows = data.loc[matching_labels]
Or even simpler, skip the index step entirely:
matching_rows = data[data.contributor_message == 'I support this proposal because...']
Only use iloc when you need to reference rows by their physical position (e.g., "give me the first 5 rows" with iloc[:5], or "give me the 10th row" with iloc[9]).
内容的提问来源于stack exchange,提问作者RyanKao

