1

I have a dataframe below that contains mapping between french to english

df1 

french english
ksjks  an
sjk    def
ssad   sdsd

And another dataframe columns are in french so need to convert them into english by using df1

df2

ksjks sjk ssad
2     4    6

how can we achieve that?

new_cols = []
for col in df2.columns:
    if col in df1['french']:
             how to get corresponding english value

PS: Have just put random data in for sample

2 Answers 2

2

Option 1
Use map with set_index

df2.columns = df2.columns.map(df1.set_index('french').english)
print(df2)

Option 2
Use rename with set_index:

df2.rename(columns=df1.set_index('french').english.to_dict())

Both produce:

   an  def  sdsd
0   2    4     6

Order of the columns doesn't matter:

df1 = pd.DataFrame({'french': ['un', 'deux', 'trois'], 'english': ['one', 'two', 'three']})
df2 = pd.DataFrame([[1,2,3]], columns=['trois', 'deux', 'un'])

df2.rename(columns=df1.set_index('french').english.to_dict())

   three  two  one
0      1    2    3

df2.columns.map(df1.set_index('french').english)
# Index(['three', 'two', 'one'], dtype='object')
Sign up to request clarification or add additional context in comments.

3 Comments

it says :TypeError: 'Series' object is not callable plus it is not necessary that order of french values are in same order as columns of other dataframe
it is not necessary that order of french values are in same order as columns of other dataframe
That shouldn't make a difference here.
0
df_lookup= pd.DataFrame({"French":["ksjks","sjk","ssad"],"english": 
["an","def","sdsd"]})

df_actual=pd.DataFrame({"ksjks":[2],"sjk":[4],"ssad":[6]})

df_actual.columns=[ df_lookup.loc[df_lookup.loc[df_lookup["French"]== 
col].index[0],"english"] for col in df_actual.columns]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.