Pandas iloc筛选数据报错,如何修复行条件+列切片问题?
First, let's address the syntax error in your code: the [:2] in the column position of iloc is invalid syntax. In Python, you can't use a slice like that without referencing an object—you need to use just :2 to indicate the first two columns.
But even with that fix, using iloc for row filtering based on a column value isn't the most intuitive approach in pandas. Let's walk through the correct ways to achieve your goal:
Solution 1: Fix the iloc Syntax
If you want to stick with iloc, correct the column slice and ensure your row condition is properly formatted:
# Corrected iloc approach data.iloc[data['three'] > 5, :2]
This works because:
data['three'] >5creates a boolean Series where each entry isTrueif the 'three' column value is greater than 5.:2tellsilocto select the first two columns (integer positions 0 and 1).
Solution 2: Use loc for More Readable Row Filtering
A better practice is to use loc when filtering rows based on column values (since loc is designed for label-based indexing), then select the first two columns (either by name or position):
By Column Name (Explicit)
If you know the exact column names you want:
data.loc[data['three'] >5, ['one', 'two']]
By Column Position (Flexible)
If you want the first two columns regardless of their names:
data.loc[data['three'] >5].iloc[:, :2]
This first filters the rows with loc, then uses iloc to grab the first two columns from the filtered result.
Example Output
All of the above solutions will return:
one two Colorado 4 5 Utah 8 9 New York 12 13
内容的提问来源于stack exchange,提问作者Anonamous Core

