如何检查pandas中另一个数据帧中是否存在值?

问题描述 投票:1回答:2

我有一个下面的数据框,其中包含法语到英语的映射

df1 

french english
ksjks  an
sjk    def
ssad   sdsd

另一个数据帧列是法语的,因此需要使用df1将它们转换为英语

df2

ksjks sjk ssad
2     4    6

我们怎样才能做到这一点?

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

PS:刚刚将随机数据放入样本中

python pandas
2个回答
2
投票

选项1 使用mapset_index

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

选项2 使用renameset_index

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

两者都产生:

   an  def  sdsd
0   2    4     6

列的顺序无关紧要:

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

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]
© www.soinside.com 2019 - 2024. All rights reserved.