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

如何用for循环合并284个DataFrame中符合条件的行至新DataFrame

汇总多个DataFrame结果的实现方案

核心思路

先初始化一个空的结果DataFrame,遍历列表里的每个DataFrame,执行你已有的单DataFrame处理逻辑,最后把每个处理后的小DataFrame合并到结果中即可。

完整代码示例

import pandas as pd

# 初始化空的结果容器
result_df = pd.DataFrame()

# 遍历所有目标DataFrame
for df in dataframes_list:
    # 取当前DataFrame的最后20行
    last_20_rows = df.tail(20)
    # 执行你指定的去重逻辑(保留Buy/Sell列组合不重复的行)
    filtered_rows = last_20_rows.drop_duplicates(subset=["Buy", "Sell"], keep=False)
    # 将筛选后的行追加到结果DataFrame
    result_df = pd.concat([result_df, filtered_rows], ignore_index=True)

补充说明

  1. 索引处理:ignore_index=True会重置合并后DataFrame的索引,避免出现重复索引问题;如果需要保留原DataFrame的索引,可以去掉这个参数。
  2. 需求适配调整:如果你的实际需求是筛选Buy/Sell列存在非空值的行(而非去重),可以在去重前增加筛选逻辑:
    # 先筛选Buy或Sell不为空的行
    filtered_rows = last_20_rows[(last_20_rows["Buy"].notna()) | (last_20_rows["Sell"].notna())]
    # 再执行去重(如果需要的话)
    filtered_rows = filtered_rows.drop_duplicates(subset=["Buy", "Sell"], keep=False)
    
  3. 性能优化:如果284个DataFrame数据量较大,建议先把所有处理后的小DataFrame存入列表,最后一次性合并,比循环中逐次合并效率更高:
    temp_list = []
    for df in dataframes_list:
        last_20_rows = df.tail(20)
        filtered_rows = last_20_rows.drop_duplicates(subset=["Buy", "Sell"], keep=False)
        temp_list.append(filtered_rows)
    result_df = pd.concat(temp_list, ignore_index=True)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 18:27:39