Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 376
13sen1 Avatar asked Jun 06 '19 14:06

13sen1


1 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
like image 146
cs95 Avatar answered Oct 05 '22 03:10

cs95