0

I have three dataframes with a column that has the same name ("col_0") in all three dfs:

>>> df_a Date col_0 0 1/22/2020 4.0 1 1/23/2020 1.2 >>> df_b Date col_0 0 1/22/2020 4.1 1 1/23/2020 1.3 >>> df_c Date col_0 0 1/22/2020 4.2 1 1/23/2020 1.5 

I want to rename each column in each df with different name in a list of names new = ["A","B","C"] using a loop but I was unable to do so. I already tried using a comprehension list to name each column but I get 9 dataframes (three of each dataframes with the new names from the new list).

>>> [i.rename(columns={'col_0':j}) i for i in [df_a,df_b,df_c] for j in ["A","B","C"]] 

But the output I really need:

>>> df_a Date A 0 1/22/2020 4.0 1 1/23/2020 1.2 >>> df_b Date B 0 1/22/2020 4.1 1 1/23/2020 1.3 >>> df_c Date C 0 1/22/2020 4.2 1 1/23/2020 1.5 

Any ideas how I can get that output. First of all, Thanks.

1
  • Simply use zip for elementwise looping. Commented Mar 26, 2020 at 20:50

2 Answers 2

2

IIUC

df_a,df_b,df_c=[i.rename(columns={'col_0':j}) for i, j in zip([df_a,df_b,df_c],["A","B","C"])] df_a Out[565]: Date A 0 1/22/2020 4.0 1 1/23/2020 1.2 
Sign up to request clarification or add additional context in comments.

Comments

0

Try to use nested loops:

columns = ['A', 'B', 'C'] dfs = [df_1, df_2, df_3] for column in columns: for df in dfs: df.rename(columns={'col_0': column}) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.