1

I have a dataframe with 5 columns, say 'A', 'B', 'C', 'D', and 'E'. I only want to add a prefix to columns 'D' and E. I have tried the following, but got an error message saying "Index does not support mutable operations".

df.columns[-2:] = [str(col) + 'Ind_' for col in ['D','E']]

How do I fix this or is there any other way to achieve what I wanted? Thanks.

1
  • 1
    try : df.rename(columns = lambda col: f"Ind_{col}" if col in ('D', 'E') else col) or do an assignment to the columns : df.columns = [f"Ind_{col}" if col in ('D', 'E') else col for col in df]. Indexes are not mutable, so you have to create a new index altogether. Commented Sep 3, 2021 at 5:15

2 Answers 2

4

Reason your code doesn't work:

Indexes are not mutable, they're Index objects, so you would have to modify all columns altogether. It doesn't support slice assignment.

Just the same as tuples, tuples are also mutable therefore tuples also don't support slicing assignment.

As you can see:

>>> a = (1, 2, 3)
>>> a[:2] = (100, 200)
Traceback (most recent call last):
  File "<pyshell#106>", line 1, in <module>
    a[:2] = (100, 200)
TypeError: 'tuple' object does not support item assignment
>>> 

Would also give an error.

Solutions:

Something like:

df.columns = np.concatenate([df.columns[:-2], df.columns[-2:] + 'Ind_'])

Or:

df = df.rename(columns = lambda x: f"{x}Ind_" if x in {'D', 'E'} else x)

Or:

df = df.set_axis(np.concatenate([df.columns[:-2], df.columns[-2:] + 'Ind_']), axis=1)

Or this way with concat:

df = pd.concat([df.iloc[:, :-2], df.iloc[:, -2:].add_suffix('Ind_')], axis=1)

Also this way with join:

df = df.iloc[:, :-2].join(df.iloc[:, -2:].add_suffix('Ind_'))
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for listing out so many solutions. Which one would you recommend?
@Jamie Probably the last two or maybe the first one
1

You can use rename method:

df = df.rename(columns = {
    'D':'Ind_D',
    'E':'Ind_E'
})

2 Comments

Thanks for your answer. I originally tried this. It works, but I think if I want to change more columns in the future, it's not the best way. Also, I'd like to include it in a function to add different suffixes, so it's not good to hard code it.
yup you are right :) U12-Forward's answer is better for you in this case.

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.