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

如何读取数百个CSV文件最后一行并合并为单个DataFrame

问题描述

尝试读取数百个CSV文件,通过.tail(1)提取每个文件的最后一行,再用pd.concat()合并为DataFrame。但结果里每个数据行都附带表头,还存在多余的Unnamed:0索引列,想要生成仅顶部有统一表头、无多余索引列的合并DataFrame。

用户当前代码:

count = 0

with open('names.txt', 'r') as my_file: 
    newline_break = "" 
    for readline in my_file: 
        line_strip = readline.strip() 
        newline_break += line_strip 
        count +=1
        
        try:

            df = pd.read_csv('~/' + line_strip + '.csv', 
                             index_col=None,
                            )
            
            df2 = df.tail(1)
            
            df3 = pd.concat([df2])
            
            print(df3)
            
        except Exception as e: 
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(exc_type, fname, exc_tb.tb_lineno) 
解决方案

问题分析

  1. 重复表头:每次循环单独合并并打印单个行的DataFrame,导致每个片段都带表头,应该先收集所有行到列表,最后一次性合并。
  2. 多余Unnamed:0列:原CSV文件保存时可能附带了索引列,读取时未处理,导致生成多余列。
  3. 冗余变量:newline_break累加文件名但未使用,属于无效代码。

修正后的代码

import pandas as pd
import sys
import os

# 初始化列表存储所有提取的行
all_last_rows = []

with open('names.txt', 'r') as my_file: 
    for readline in my_file: 
        line_strip = readline.strip() 
        # 跳过空行,避免读取无效文件名
        if not line_strip:
            continue
            
        try:
            # 读取时跳过原文件的索引列(解决Unnamed:0问题)
            df = pd.read_csv(f'~/{line_strip}.csv', index_col=0)
            # 提取当前文件最后一行
            last_row = df.tail(1)
            # 将行添加到列表
            all_last_rows.append(last_row)
            
        except Exception as e: 
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print(f"错误类型: {exc_type}, 文件: {fname}, 行号: {exc_tb.tb_lineno}") 

# 合并所有行,重置索引避免混乱
final_df = pd.concat(all_last_rows, ignore_index=True)
# 兜底处理:如果仍有Unnamed列,直接删除
final_df = final_df.drop(columns=[col for col in final_df.columns if 'Unnamed' in col])
# 输出最终合并结果
print(final_df)

关键说明

  • 先收集后合并:用列表存储所有文件的最后一行,最后一次性合并,确保仅保留一个统一表头。
  • 处理多余索引列:通过index_col=0读取时直接跳过原文件的索引列;若不确定索引列位置,可读取后删除所有含Unnamed的列。
  • 重置索引:concat时添加ignore_index=True,避免原文件的索引干扰最终结果的连续性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 22:20:30