How to add prefix to only certain columns in python
Question:
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.
Answers:
You can use rename method:
df = df.rename(columns = {
'D':'Ind_D',
'E':'Ind_E'
})
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_'))
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.
You can use rename method:
df = df.rename(columns = {
'D':'Ind_D',
'E':'Ind_E'
})
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_'))