sundaysfantasy
sundaysfantasy

Reputation: 43

Renaming columns of dataframe with values from another dataframe

so I have a dataframe that roughly looks like this:

name1   name2   name3
123     456     678
123     456     678
123     456     678

and another dataframe that looks like this

name2  abc
name3  cdf
name1  fgh

Is there any way I can make the first dataframe column names like this:

fgh     abc     cdf
123     456     678
123     456     678
123     456     678

Thanks.

Upvotes: 2

Views: 1153

Answers (2)

BENY
BENY

Reputation: 323236

You can using Series get and assign it back

df.columns=s.get(df.columns)
df
Out[223]: 
s1  fgh  abc  cdf
0   123  456  678
1   123  456  678
2   123  456  678

Upvotes: 0

jezrael
jezrael

Reputation: 862661

Use rename by Series with set_index for index by column A:

print (df2)
       A    B
0  name2  abc
1  name3  cdf
2  name1  fgh

df1 = df1.rename(columns=df2.set_index('A')['B'])
print (df1)
   fgh  abc  cdf
0  123  456  678
1  123  456  678
2  123  456  678

Detail:

print (df2.set_index('A')['B'])
A
name2    abc
name3    cdf
name1    fgh
Name: B, dtype: object

Or by dictionary created by zip:

df1 = df1.rename(columns=dict(zip(df2.A, df2.B)))

Detail:

print (dict(zip(df2.A, df2.B)))
{'name3': 'cdf', 'name1': 'fgh', 'name2': 'abc'}

Upvotes: 1

Related Questions