Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading