How to replace columns names in pandas but based on dictionary?

Viewed 1209

I have 4 different dfs. Example of column names:

df1 = a1, b1, c1, d1
df2 = b1, c1, e1
df3 = a1, b1, c1

And I created dicrionary like this:

dict = {a1:art1, b1:base1, c1:cell1, d1:dan1, e1:el1}

It's possible to rename column not using for loop? I mean, I tried to do that by rename function in for loop, but then I need to loop through all dataframe and it's not looks good in code and I think it's not that fast as should be.

My excpected result is:

df1 = art1, base1, cell1, dan1
df2 = base1, cell1, el1
df3 = art1, base1, cell1

And I found some answers on stack but nothing fit to my problem, where I have one dictionary and few df with not unique columns names.

1 Answers

A comprehension:

d = {'a1': 'art1', 'b1': 'base1', 'c1': 'cell1', 'd1': 'dan1', 'e1': 'el1'}

df1, df2, df3 = [df.rename(columns=d) for df in [df1, df2, df3]]

A simple loop:

for df in [df1, df2, df3]:
    df.rename(columns=d, inplace=True)

Using map:

df1, df2, df3 = list(map(lambda df: df.rename(columns=d), [df1, df2, df3]))

At the end, IMHO the simple loop with inplace=True is the most elegant.

Related