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

如何遍历DataFrame行并将符合条件的行追加至另一个DataFrame?

解决Pandas遍历行追加DataFrame的问题

最优方案:用布尔索引直接筛选(避免循环)

Pandas的设计核心是向量化操作优先,循环遍历行效率极低且易出结构问题,直接用布尔索引筛选符合条件的行是最优解:

# 直接生成符合条件的新DataFrame
some_other_df = df[df['Column'] == some_value].copy()

# 如果需要追加到已存在的some_other_df
some_other_df = pd.concat(
    [some_other_df, df[df['Column'] == some_value].copy()],
    ignore_index=True
)

这种方式返回完整的DataFrame结构,完全不存在拼接异常,且处理速度远快于循环。

特殊场景需循环时的处理方法

如果业务逻辑必须逐行处理(比如追加前需对行做额外修改),需要把遍历得到的Series转为单行DataFrame再拼接:

方法1:列表收集后一次性concat(推荐,效率更高)

temp_rows = []
for _, row in df.iterrows():
    if row['Column'] == some_value:
        # 将Series转成单行DataFrame
        temp_rows.append(row.to_frame().T)

# 一次性拼接所有行
some_other_df = pd.concat(temp_rows, ignore_index=True)

方法2:逐行append(不推荐,频繁append会导致性能下降)

# 初始化空DataFrame,确保列结构与源df一致
some_other_df = pd.DataFrame(columns=df.columns)

for _, row in df.iterrows():
    if row['Column'] == some_value:
        some_other_df = some_other_df.append(row.to_frame().T, ignore_index=True)

核心是row.to_frame().T:先把行Series转成列格式的DataFrame,再转置为行格式,让结构与目标DataFrame匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:15:43