Pandas DataFrame多列批量重命名及列偏移调整问题
Got it, dealing with column misalignment on a huge DataFrame is a pain—especially with 300 columns, renaming each one manually is totally out of the question. Here are two efficient fixes for you:
Fix 1: Correct the already loaded misaligned DataFrame
Your current DataFrame has columns shifted right by one, with a final column full of NaNs. We can fix this in two quick slicing steps:
# Extract the correct column names (shift left, drop the last empty one) new_columns = df.columns[1:-1].tolist() # Slice the data to remove the first shifted column and last NaN column, then set new names df = df.iloc[:, 1:-1] df.columns = new_columns
Breakdown:
df.columns[1:-1]: Grabs all column names starting from the second one up to the second-to-last one, which are your actual desired column headers.df.iloc[:, 1:-1]: Removes the first extraneous column (from the shift) and the final all-NaN column from your data.- Assigning
new_columnsto the sliced DataFrame aligns everything perfectly.
Fix 2: Avoid misalignment entirely when reading the CSV
Looking at your CSV content, the first line is a comment header, and the second line is your actual column names. You can read the CSV correctly in one step by skipping that first comment line and letting pandas use the second line as headers:
import pandas as pd # Skip the first comment line, use the second line as column headers df = pd.read_csv('myCSV.csv', skiprows=1)
This reads the data directly into a properly aligned DataFrame, no post-processing needed. For your sample CSV, the output of df.head(2) will look exactly like what you want:
| LocalTime | Temp | TempDiff | TempNormal | DewPoint | Cloud Cover | FeelsLikeTemp |
|---|---|---|---|---|---|---|
| 5/16/2018 0:00 | 68 | -3.38 | 57.5 | 66.92 | 100 | 68 |
| 5/16/2018 1:00 | 66.92 | -3.89 | 55.22 | 66.92 | 100 | 66.92 |
内容的提问来源于stack exchange,提问作者Zanam

