junky
junky

Reputation: 21

Renaming columns in Pandas DataFrame not working

I created a Pandas DataFrame which has column names 0,1,2.. and am trying to rename them, but the rename function is not working.

my code:

complete_list is a list of lists, which i would like to convert to csv.

output_csv = pd.DataFrame(complete_list) 
output_csv.rename(columns={'0':'dpinID', '1': 'latin_name', '2': 'common_names'})
output_csv.to_csv('output.csv')

this is the head of the dataframe complete_list

Upvotes: 2

Views: 5420

Answers (1)

inspectorG4dget
inspectorG4dget

Reputation: 113955

The problems you face are caused by two issues:

  1. .rename(...) returns a new DataFrame, rather than altering the existing dataframe in-place
  2. The renaming dictionary uses stringified integers for the source names, instead of the actual int value

The fix is rather simple:

output_csv.rename(columns={0:'dpinID', 1: 'latin_name', 2: 'common_names'}, inplace=True)

Upvotes: 3

Related Questions