简体   繁体   中英

How to check if value exists in another dataframe in pandas?

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

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')
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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM