Python Forum

Full Version: Rename first row in a CSV file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I don't know what I have done wrong. I want to rename the first row of the table:
renamed_df = pd.read_csv('my_data.csv')

# Change column names
renamed_df.rename(columns={'AA': 'aaa', 'BB': 'bbb', 'CC': 'ccc', 'DD': 'ddd', 'EE': 'eee'}, inplace=True)

# Save the renamed DataFrame to a new CSV file
renamed_df.to_csv('renamed_my_data.csv', index=False)

renamed_df.head()
Input (my_data.csv):

39, AA, BB, CC, DD, EE
40, 111,222,333,444,555
41,666,777,888,999,000
42,121,232,343,454,565
43,244,355,366,377,388

Expected output (renamed_my_data.csv)

39, aaa, bbb, ccc, ddd, eee
40, 111,222,333,444,555
41,666,777,888,999,000
42,121,232,343,454,565
43,244,355,366,377,388
Your first column name is " AA", not "AA". You need to tell pandas that there may be extra whitespace
df = pd.read_csv('my_data.csv', skipinitialspace=True)
deanhystad,

Thank you. It works.