Rename only the last column in pandas dataframe (accounting for duplicate headers)

Question:

I need to rename only the last column in my dataframe, the issue is there are many columns with the same name (there is a reason for this), thus I cannot use the code in other examples online. Is there a way to use something specific that just isolates the final column?

I have tried to do something like this
df.rename(columns={df.columns[-1]: 'Test'}, inplace=True)

However this then means that all columns with that same header are changed to ‘Test’, whereas I just want the last one to change.

I kind of need something like df.columns[-1] = 'Test' but this doesn’t work.

Asked By: 13sen1

||

Answers:

You can always explicitly reassign.

df.columns = [*df.columns[:-1], 'Test']

Or, if you want to method chain, use set_axis the same way:

df.set_axis([*df.columns[:-1], 'Test'], axis=1, inplace=False)

Minimal Code Example

df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=list('ABA'))
df

   A  B  A
0  1  2  3
1  4  5  6
2  7  8  9

df.rename({df.columns[-1]: 'C'}, axis=1) # wrong

   C  B  C
0  1  2  3
1  4  5  6
2  7  8  9

df.set_axis([*df.columns[:-1], 'Test'], axis=1, inplace=False)

   A  B  Test
0  1  2     3
1  4  5     6
2  7  8     9
Answered By: cs95

Thank you!
I am just wondering. What does the asterisk(*) here mean or why we need it?
‘df.set_axis([*df.columns[:-1], ‘Test’], axis=1, inplace=False)’

Answered By: sergio
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.