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

2024-06-28 19:45:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

df1 

french english
ksjks  an
sjk    def
ssad   sdsd

另一个dataframe列是法语的,所以需要使用df1将它们转换成英语

^{pr2}$

我们如何才能做到这一点?在

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

附言:刚把随机数据放入样本中


Tags: 数据inandataframenewenglishdefcol
2条回答

选项1
mapset_index一起使用

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

选项2
renameset_index一起使用:

^{pr2}$

两者都产生:

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

相关问题 更多 >