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

Python中提取DataFrame符合条件行至新DataFrame的合并问题

问题解决:从DataFrame提取指定行到另一个DataFrame

你的核心问题是循环里用concat合并时失败,本质是因为entry是Series(一维结构),直接和DataFrame合并会导致结构不匹配——pandas会把Series当成一列来拼接,而不是一行。下面给你两种解决方案,优先推荐第一种Pythonic的实现方式:

1. 最优实现:直接批量筛选(告别循环)

不用逐行遍历,利用pandas的向量式操作一次性筛选所有符合条件的行,效率和简洁性都远高于循环:

import pandas as pd

# 一次性筛选GL_Account前7位等于"4000001"的所有行
filtered_rows = dfExtract[dfExtract['GL_Account'].str[:7] == "4000001"]

# 合并到目标DataFrame,ignore_index=True避免索引重复
dfglisolation = pd.concat([dfglisolation, filtered_rows], ignore_index=True)

从C++转Python要尽量摆脱“逐行处理”的思维,pandas的整列操作是专门优化过的,大数据量下性能比循环高几个量级。

2. 修复你的循环代码(如果必须保留循环逻辑)

如果因为其他需求一定要用循环,只需把Series转成单行DataFrame再合并:

if dfExtract.at[highIter, 'GL_Account'][:7] == "4000001":
    # 用双层括号loc[[highIter]],得到的是单行DataFrame而非Series
    entry = dfExtract.loc[[highIter]]
    dfglisolation = pd.concat([dfglisolation, entry], ignore_index=True)

原来的dfExtract.loc[highIter]返回的是一维Series,合并时会被当成列处理;改成loc[[highIter]]就能得到结构匹配的单行DataFrame。

补充提示

如果dfglisolation是新建的空表,记得先初始化和原表结构一致:

dfglisolation = pd.DataFrame(columns=dfExtract.columns)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 16:32:22