Search code examples
pythonpandasdataframerename

Renaming multiple columns using their index


How can i rename multiple columns of a dataframe using their index? For example i want to rename the columns at positions 5,6,7,8 to 'five','six','seven','eight' respectively. I don't want to enter the keys in the dictionary individually.


Solution

  • In the case of already having a dictionary, you can use rename to map to the new axis values:

    df = pd.DataFrame(columns=range(10))
    d = {5:'five', 6:'six', 7:'seven', 8:'eight'}
    df = df.rename(d, axis=1)
    # Index([0, 1, 2, 3, 4, 'five', 'six', 'seven', 'eight', 9], dtype='object')
    

    Or, as @ch3ster points out, rename takes both index and column parameters allowing to rename both independently:

    df = df.rename(columns=d)
    

    In the case you know the range of columns to rename, and have a list of new column names, you could build a dictionary as and rename with:

    l = ['five', 'six', 'seven', 'eight', 'nine']
    df = df.rename(columns=dict(zip(range(5,9), l)))