Rename Column Name in Pandas DataFrame

You can change one or more column names of your pandas DataFrame with rename() method. Let’s see the sample below:

  • First: Create pandas DataFrame and print the data
  • Second: Change two column names from ($fname, $mname) to ($first_name, $middle_name)
  • Third: Remove the $ character from all column names

Sample:

    import pandas as pd
    
    data = {
        '$id': ['1', '2', '3'], 
        '$fname': ['Andy', 'Mark', 'Twain'], 
        '$mname':   ['Law', 'Zack', 'Beam'], 
    }
    
    print("First")
    df = pd.DataFrame(data)
    print(df, end='\n\n')
    
    print("Second")
    df.rename(columns = {'$fname': '$first_name', '$mname': '$middle_name'}, inplace = True)
    print(df, end='\n\n')
    
    print("Third")
    df.columns = df.columns.str.replace('$', '', regex = True)
    print(df)

    On the Second script above, on the df.rename() method, inplace = True, to update in current DataFrame. And on the Third script, regex = True to prevent from warning below:

    FutureWarning: The default value of regex will change from True to False in a future version. In addition, single character regular expressions will *not* be treated as literal strings when regex=True.
      df.columns = df.columns.str.replace('$', '')

    Output:

    rename_column_names_in_pandas_dataframe

    Leave a comment