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

如何将DataFrame求和行移至首行?批量处理280个CSV文件遇阻

Solution: Add a Total Row at the Top of Each CSV File

Got it, let's fix this up for you. The issue with your current code is that you're adding a column of sums instead of a row—let's adjust that to create the total row and place it at the top of each DataFrame, then apply this to all 280 CSV files.

Step-by-Step Approach

  1. Read each CSV file with your existing parameters.
  2. Calculate the sum of all numeric columns to create a total row.
  3. Fill non-numeric columns in the total row with a meaningful label (like "Total") to match the original DataFrame's structure.
  4. Combine the total row with the original DataFrame, placing the total row first.
  5. Save the modified DataFrame back to the CSV file.

Full Code Example

import pandas as pd
import os

# Set the path to your folder containing all CSV files
csv_directory = "/path/to/your/csv/files"

# Loop through every file in the directory
for filename in os.listdir(csv_directory):
    if filename.endswith(".csv"):
        file_path = os.path.join(csv_directory, filename)
        
        # Read the CSV with your specified parameters
        df = pd.read_csv(file_path, sep=";", header=2, engine="python")
        
        # Calculate sums for numeric columns only
        total_row = df.sum(numeric_only=True)
        
        # Fill non-numeric columns in the total row (customize this label as needed)
        for column in df.columns:
            if column not in total_row.index:
                total_row[column] = "Total"
        
        # Convert the total row to a DataFrame to concatenate with the original
        total_df = pd.DataFrame([total_row.values], columns=df.columns)
        
        # Combine the total row at the top of the original DataFrame
        updated_df = pd.concat([total_df, df], ignore_index=True)
        
        # Save the modified CSV (overwrites the original; adjust if you want to keep copies)
        updated_df.to_csv(file_path, sep=";", index=False)

Key Notes

  • Non-numeric Column Handling: The code fills non-numeric columns with "Total"—you can change this to an empty string ("") or another label if that makes more sense for your data.
  • Overwriting Files: The code overwrites the original CSV files. If you want to keep backups, modify the to_csv path to save to a new folder (e.g., os.path.join("modified_csvs", filename)).
  • Index Reset: Using ignore_index=True ensures the combined DataFrame has a clean, sequential index without conflicts.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:38:15