2

I would like to rename column 1 of the following dataframe as 'Ref'. I have many columns and thus can't rename each or set names for each.

data = [['TC1', 103, 563], ['TC2', 1567, 1290], ['TC3', 1467, 567]] 

dftrash=pd.DataFrame(data, columns = ['Card', '', '']) 

This is the dataframe

    Card        
0   TC1 1037    8563
1   TC2 1567    1290
2   TC3 1467    567

Now I want to rename the 1st column as 'Ref'. I tried this

dftrash.rename(columns={dftrash.columns[1]:'REF'},inplace=True)

which renames all columns with similar heading as column[1].


    Card REF    REF
0   TC1 1037    8563
1   TC2 1567    1290
2   TC3 1467    567
0

3 Answers 3

1

Columns in pandas are immutable - your best bet would be to make numpy array, set values by indexing and assign back:

#pandas 0.24+
a = dftrash.columns.to_numpy()
#pandas below
#a = dftrash.columns.to_numpy()
a[1] = 'REF'
print (a)
['Card' 'REF' '']

Or convert values to list:

a = dftrash.columns.tolist()
a[1] = 'REF'
print (a)
['Card', 'REF', '']

dftrash.columns = a
print (dftrash)
  Card   REF      
0  TC1   103   563
1  TC2  1567  1290
2  TC3  1467   567

In past versions of pandas was problem assign to numpy array, it seems now it working nice, but still recommended first solution:

dftrash.columns.values[1] = "REF"
print (dftrash)
  Card   REF      
0  TC1   103   563
1  TC2  1567  1290
2  TC3  1467   567
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks jezrael! This is of course a way. I was wondering whether a renaming by indexing such as rename(columns={1:'Ref'}) is possible someway. I found this renaming by index in some threads but does not work.
@haphaZard - no, it not working, because duplicated columns names, so need another solutions like in answer.
0

You could extract the columnnames, edit the column name, and insert again

data = [['TC1', 103, 563], ['TC2', 1567, 1290], ['TC3', 1467, 567]]
dftrash=pd.DataFrame(data, columns = ['Card', '', '']) 
colnames = list(dftrash.columns)
colnames[1] = "REF"
dftrash.set_axis(colnames, axis=1, inplace=True)

Comments

0

I think this will do the job:

dftrash.columns = ['REF'] + list(dftrash.columns[1:])

It, basically, creates new name list that pandas can use to rename columns. Or more generally:

new_names = list(dftrash.columns)
new_names[0] = 'REF'
dftrash.columns = new_names

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.