pythonpandasdataframeloops

Iterating over each dataframe in a list of dataframes and changing name of first column


I'm trying to iterate through a list of datraframes and do two things, replace blanks with "_" (which I've done) and add a suffix to the first column of each dataframe. I know I can access the first column of the each dataframe via the print row within the loop below, but I'm having trouble adding the suffix to the first column. Can someone please help?

Sample data:

import pandas as pd

px_data = {'Date': ['8/11/18', '8/12/18', '8/13/18', '8/14/18'],
        'A df': [58.63, 21.25, 19.17, 18.8],
        'B df': [35,105,27,98]}

SC_data = {'Date': ['8/11/18', '8/12/18', '8/13/18', '8/14/18'],
        'A df': [20.50, 6, 82, 74.6],
        'B df': [74,62,8,99]}

SMA_data = {'Date': ['8/11/18', '8/12/18', '8/13/18', '8/14/18'],
        'A df': [2, 95.3, 39, 68.27],
        'B df': [58,37,74,11]}

px = pd.DataFrame(px_data)
SC = pd.DataFrame(SC_data)
SMA = pd.DataFrame(SMA_data)

dfs=[px,SC,SMA]
   
for i in range(len(dfs)):
    dfs[i].columns = dfs[i].columns.str.replace(' ', '_')
    print(dfs[i].columns[0])

Solution

  • After replacing blanks with underscore, you can add suffix to the first columns of each dataframe in the following way:

    first_column = dfs[i].columns[0] # get first column
    dfs[i].rename(columns={first_column: first_column + '_suffix'}, inplace=True) # Add a suffix to the first column