如何批量将CSV多列秒级CPU时间转为小时(免分步处理)
If you're looking to convert multiple CPU time columns from seconds to hours in one go while keeping the original CSV structure intact, here are two reliable approaches:
Python Pandas (Flexible, Handles Complex CSVs)
Pandas is ideal here because it lets you target specific columns, preserves data types, and maintains the original CSV format perfectly.
Here's a script you can use:
import pandas as pd # Load your CSV file (adjust delimiter if needed, e.g., delimiter=';') df = pd.read_csv('cpu_times.csv') # Choose which columns to convert—you can list them explicitly or exclude non-numeric ones # Example 1: Exclude a user ID/name column (replace 'username' with your actual column name) columns_to_convert = df.columns.drop('username') # Example 2: Convert all numeric columns automatically # columns_to_convert = df.select_dtypes(include=['number']).columns # Perform the conversion (divide by 3600 to get hours) df[columns_to_convert] = df[columns_to_convert] / 3600 # Optional: Round to a specific number of decimal places (e.g., 4) # df[columns_to_convert] = df[columns_to_convert].round(4) # Save back to CSV without adding an extra index column df.to_csv('cpu_times_hours.csv', index=False)
This script will:
- Keep your header row exactly as it was
- Leave non-target columns (like usernames) unchanged
- Preserve the original delimiter and quoting behavior
- Convert all specified columns to hours in one step
Awk (Command-Line, No Dependencies)
If you prefer a command-line solution without installing libraries, awk works great for simple CSVs (no commas inside quoted fields).
Basic Conversion (No Decimal Formatting)
awk -F ',' 'BEGIN {OFS=","} NR==1 {print; next} {for(i=2; i<=NF; i++) $i = $i / 3600} 1' cpu_times.csv > cpu_times_hours.csv
With Decimal Precision (e.g., 4 Decimal Places)
If you want to control how many decimal places are shown:
awk -F ',' 'BEGIN {OFS=","} NR==1 {print; next} { printf "%s", $1; # Print the first column (username) as-is for(i=2; i<=NF; i++) { printf "%s%.4f", OFS, $i / 3600; } print "" }' cpu_times.csv > cpu_times_hours.csv
- Replace
i=2with the starting column number if your CPU time columns start later - Adjust
%.4fto%.2ffor 2 decimal places, etc.
Both methods will produce an output CSV that matches your original file's structure—same column order, headers, and formatting—just with the CPU time values converted to hours.
内容的提问来源于stack exchange,提问作者alpha

