Issue
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.
Solution
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.