如何将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
- Read each CSV file with your existing parameters.
- Calculate the sum of all numeric columns to create a total row.
- Fill non-numeric columns in the total row with a meaningful label (like "Total") to match the original DataFrame's structure.
- Combine the total row with the original DataFrame, placing the total row first.
- 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_csvpath to save to a new folder (e.g.,os.path.join("modified_csvs", filename)). - Index Reset: Using
ignore_index=Trueensures the combined DataFrame has a clean, sequential index without conflicts.
内容的提问来源于stack exchange,提问作者Pedro Salgado
相关产品推荐
相关产品推荐

