You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas iloc筛选数据报错,如何修复行条件+列切片问题?

Fixing the Syntax Error and Correctly Filtering Your DataFrame

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'] >5 creates a boolean Series where each entry is True if the 'three' column value is greater than 5.
  • :2 tells iloc to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 14:52:40