Python Forum
Rename first row in a CSV file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Rename first row in a CSV file
#1
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()
Yoriz write Dec-17-2023, 01:19 AM:
Please post all code, output and errors (in its entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to ensure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
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
Reply
#3
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)
Reply
#4
deanhystad,

Thank you. It works.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  rename file RolanRoll 0 538 May-18-2023, 02:17 PM
Last Post: RolanRoll
  '' FTP '' File upload with a specified string and rename midomarc 1 1,173 Apr-17-2023, 03:04 AM
Last Post: bowlofred
  rename same file names in different directories elnk 0 719 Nov-04-2022, 05:23 PM
Last Post: elnk
  rename and add desire "_date" to end of file name before extention RolanRoll 1 1,250 Jun-13-2022, 11:16 AM
Last Post: gruntfutuk
  Rename Files based on XML file klturi421 3 2,208 Oct-22-2021, 07:37 PM
Last Post: klturi421
  How to rename a CSV file by adding MODIFIED in the filename? Python_User 25 8,170 Dec-13-2020, 12:35 PM
Last Post: Larz60+
  Rename docx file from tuple gjack 2 2,203 Oct-20-2020, 05:33 PM
Last Post: gjack
  Copy mp3 file multiple times and rename Mar10 4 3,766 Sep-23-2020, 01:09 AM
Last Post: Mar10
  Rename file from value in text file Nuge93 1 2,192 Jan-20-2020, 03:50 PM
Last Post: gruntfutuk
  Extract Info from file to rename file twent2t 4 3,131 Aug-05-2018, 06:51 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020