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

使用Python Pandas时如何复制DataFrame中符合条件的整行到新DataFrame

Pandas 筛选符合条件的整行数据到新DataFrame的方法

原有代码问题说明

你当前写的代码存在两个核心错误:

  • for line in file 直接遍历DataFrame时,返回的是列名而非行数据,无法按行校验筛选条件
  • 条件判断混用了行对象和原DataFrame对象,逻辑不成立

推荐实现方案(Pandas 向量化筛选,效率最优)

Pandas 原生支持按布尔条件批量筛选行,无需写循环,写法如下:

import pandas as pd

# 读取源csv文件
file = pd.read_csv("file.csv", encoding = "utf-8", sep=";")
# 按条件筛选后复制生成独立的新DataFrame
new_df = file[(file['age'] < 18) & (file['vaccinated'] == 'n')].copy()

说明:末尾加copy()是为了生成完全独立的新DataFrame,避免后续修改new_df时影响原数据。按照你提供的csv测试数据,最终new_df会保留gender=f、age=12、vaccinated=n这一行的所有字段。

循环写法参考(仅作逻辑参考,不推荐用于大数据量场景)

如果你一定要用逐行遍历的写法,可以用iterrows()方法实现:

import pandas as pd

file = pd.read_csv("file.csv", encoding = "utf-8", sep=";")
new_df = pd.DataFrame()
for index, row in file.iterrows():
    if row['age'] < 18 and row['vaccinated'] == 'n':
        # 追加符合条件的行到新DataFrame
        new_df = pd.concat([new_df, row.to_frame().T], ignore_index=True)

内容的提问来源于stack exchange,提问作者standardmarcelo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:03:04