如何检查大熊猫中另一个数据框中是否存在值?

时间:2018-09-05 03:04:25

标签: python pandas

下面有一个数据框,其中包含法语与英语之间的映射

df1 

french english
ksjks  an
sjk    def
ssad   sdsd

另外一个dataframe列为法语,因此需要使用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:刚刚将随机数据放入样本中

2 个答案:

答案 0 :(得分: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')

答案 1 :(得分: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]