pythonpandasdataframerenamelabeling

Labeling columns in Pandas but not renaming


I have a pandas dataframe with column names. These column names are not meaningful. So I want to make the columns with labels more intuitive and speaking. However, I also have many calculations based on the original names. How can I ensure that I get the dataframes with the labels displayed or that the CSV file shows the labels as column names when exporting, but at the same time that all the calculations in the code are based on the original column names?


Solution

  • Create a mapping dict and its reverse:

    dmap = {'col1': 'My first column', 'col2': 'My Second column'}
    rmap = {v: k for k, v in dmap.items()}
    
    # Before exporting
    df.rename(columns=dmap).to_csv(...)
    
    # After importing
    pd.read_csv(...).rename(columns=rmap)