简体   繁体   中英

Rename the column inside csv file

Can anyone please check for me what's wrong with my renaming command. It changes nothing on the csv file. The code that i have tried below renaming header.

df = pandas.read_csv('C:/JIRA Excel File.csv')
df.rename(columns=({'Custom field (Implemented Date)':'Custom field (Verified Date)'}))
df.set_index('Custom field (Verified Date)').to_csv("C:/JIRA Excel File/Done.csv", index=None)

I want column Custom field (Implemented Date) CHANGE to Custom field (verified Date), but the column still doesn't change.

Original CSV.file

点击这里

Now the KeyError: 'Custom field (Implemented Date)' is not execute anymore. Just after I run this code.

The output will display as below.

在此处输入图片说明

You are not assigning the result of rename back to the dataframe. Change the 2nd line to

df = df.rename(columns=({'Custom field (Implemented Date)':'Custom field (Verified Date)'}))

you can call rename function with external parameter inplace=True

df.rename(columns={'Custom field (Implemented Date)': 'Custom field (Verified Date)'}, inplace=True)

For more see pandas.DataFrame.rename and Renaming columns in pandas

Update: from your comment and updated question

# considering a sample csv from  your description and the df is.
''' 
  Issue Type Custom field (Verified Date) Custom field (Implemented Date)
0    issue-1               varified-date1               Implemented-Date1
1    issue-2               varified-date2               Implemented-Date2
'''
# first delete the 'Custom field (Verified Date)' column
del df['Custom field (Verified Date)']
'''
  Issue Type Custom field (Implemented Date)
0    issue-1               Implemented-Date1
1    issue-2               Implemented-Date2
'''
# rename the column 'Custom field (Implemented Date)' to 'Custom field (Verified Date)'
df.rename(columns={'Custom field (Implemented Date)': 'Custom field (Verified Date)'}, inplace=True)
'''
Issue Type Custom field (Verified Date)
0    issue-1            Implemented-Date1
1    issue-2            Implemented-Date2
'''
df.set_index('Custom field (Verified Date)').to_csv("Done.csv", index=None)

And after all this I get the output in file as you describe above with out any error.

You can simply use:

renamed_df=df.rename(columns={'Custom field (Implemented Date)':'Custom field (Verified Date)'})
renamed_df.to_csv("C:/JIRA Excel File/Done.csv", index=None)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM