Creating function to rename columns in pandas dataframe

Viewed 3368

I have dataframe as below:

df = pd.DataFrame({'$a':[1,2], '$b': [10,20]})

I tried creating a function which allow to change the column name dynamically where I can just input the old column name and new column name in the function as below:

def rename_column_name(df, old_column, new_column):
    df = df.rename({'{}'.format(old_column) : '{}'.format(new_column)}, axis=1)
    return df

This function is only applicable if I only have one input as below:

new_df = rename_column_name(df, '$a' , 'a')

which give me this new_df as below:

new_df = pd.DataFrame({'a':[1,2], '$b': [10,20]})

However, i wanted to create a function that allow me to make changes on multiple/one column depending on my preference as such:

new_df = rename_column_name(df, ['$a','$b'] , ['a','b'])

And get the new_df as below

new_df = pd.DataFrame({'a':[1,2], 'b': [10,20]})

So, how do I make my function more dynamic to allow me the freedom to enter multiple/one column names and rename them?

3 Answers

You don't need a function, you can do this using dict comprehension:

In [265]: old_names = df.columns.tolist()                                                                                                                                                                   

In [266]: new_names = ['a','b']                                                                                                                                                                             

In [268]: df = df.rename(columns=dict(zip(old_names, new_names)))                                                                                                                                  

In [269]: df                                                                                                                                                                                                
Out[269]: 
   a   b
0  1  10
1  2  20

Function that OP needs:

In [274]: def rename_column_name(df, old_column_list, new_column_list): 
     ...:     df = df.rename(columns=dict(zip(old_column_list, new_column_list))) 
     ...:     return df 
     ...:                                                                                                                                                                                                   

In [275]: rename_column_name(df,old_names,new_names)                                                                                                                                                        
Out[275]: 
   a   b
0  1  10
1  2  20

You need to pass a list of columns to this function. It can be multiple columns or a single column. This should do what you were looking for.

def rename_column_name(df, old_column, new_column):
    if not isinstance(old_column,(list,tuple)):
        old_column = [old_column]
    if not isinstance(new_column,(list,tuple)):
        old_column = [new_column]

    df = df.rename({'{}'.format(old) : '{}'.format(new) for old,new in zip(old_column,new_column)}, axis=1)
    return df # dang i should have used dict.zip like in the other solution :P

I guess ... although i don't understand how this is easier than just calling

df.rename(columns={'$a':'a','$b':b})

You can do that with zip function where, old_column_names and new_column_names should be lists.

def rename_column_name(df, old_column_names, new_column_names):

    //validating the such that all the new names have been passed

    if(len(old_column_names) == len(new_column_names)):
        df = df.rename(columns=dict(zip(old_column_names, new_column_names)), inplace=True)
    return df  

To handle both one column rename and passing them as lists the function would require further conditions which can be

 def rename_column_name(df, old_column_names, new_column_names):

    //validating the such that all the new names have been passed
    if(isinstance(old_column_names, list)) and (isinstance(new_column_names, list)):
        if(len(old_column_names) == len(new_column_names)):
            df = df.rename(columns=dict(zip(old_column_names, new_column_names)), inplace=True)
    elif (isinstance(old_column_names, str)) and (isinstance(new_column_names, str)):
        df = df.rename(columns={'{}'.format(old_column_names) : '{}'.format(new_column_names)}, inplace=True)
    return df 
Related