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
haphaZard
  • 43
  • 1
  • 6

3 Answers3

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
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • 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 Jun 18 '19 at 12:09
  • @haphaZard - no, it not working, because duplicated columns names, so need another solutions like in answer. – jezrael Jun 18 '19 at 12:10
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
DmytroSytro
  • 579
  • 4
  • 15
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)
Oliver Olsen
  • 104
  • 2
  • 8