Skip to content Skip to sidebar Skip to footer

Renaming Columns On Slice Of Dataframe Not Performing As Expected

I was trying to clean up column names in a dataframe but only a part of the columns. It doesn't work when trying to replace column names on a slice of the dataframe somehow, why is

Solution 1:

This is because pandas' index is immutable. If you check the documentation for class pandas.Index, you'll see that it is defined as:

Immutable ndarray implementing an ordered, sliceable set

So in order to modify it you'll have to create a new list of column names, for instance with:

df.columns = [df.columns[0]] + list(df.iloc[:, 1:].columns.str[:4])

Another option is to use rename with a dictionary containing the columns to replace:

df.rename(columns=dict(zip(df.columns[1:], df.columns[1:].str[:4])))

Solution 2:

I had this problem as well and came up with this solution:

First, create a mask of the columns you want to rename

mask = df.iloc[:,1:4].columns

Then, use list comprehension and a conditional to rename just the columns you want

df.columns = [x if x not in mask elsestr[:4] forxin df.columns]

Solution 3:

To overwrite columns names you can .rename() method:

So, it will look like:

df.rename(columns={'ColA_fjkj':'ColA',
                   'ColB_huqwa':'ColB',
                   'ColC_ouiqw':'ColC'}
          , inplace=True)

More info regarding rename here in docs: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename.html

Post a Comment for "Renaming Columns On Slice Of Dataframe Not Performing As Expected"