luanstat
luanstat

Reputation: 65

How to rename duplicate columns in multiple dataframes using pandas?

I have the script below which I am using the rename columns in df1, and it is working fine. I have to run this for multiple different dataframes, df2, df3, etc. Currently I am copying and pasting the name of the table and rerunning the script, What is the best way to iterate through each df without having to copy and paste df1, df2, etc.

cols=pd.Series(df1.columns)
for dup in cols[cols.duplicated()].unique(): 
    cols[cols[cols == dup].index.values.tolist()] = [dup + '_' + str(i) ...

Upvotes: 0

Views: 172

Answers (1)

Ulewsky
Ulewsky

Reputation: 329

Maybe sth like that will help

frames = [d1,d2,d3,d4,...]
for frame in frames:
    cols = pd.Series(frame.columns)
    for dup in cols[cols.duplicated()].unique():
        cols[cols[cols == dup].index.values.tolist()] = [dup + '_' + str(i)...

Upvotes: 1

Related Questions