首页 > 解决方案 > 使用多个数据框合并左侧

问题描述

如果不清楚,我会尝试解释我的问题,请原谅。我有这个数据源,我创建了三个函数来合并两个数据框。我的源代码的前五行:

DF=pd.read_excel(path)
DF.rename(columns={"localisation":"Description"},inplace=True)
DF.head()

在此处输入图像描述

我创建了四个函数来在我的 DF 中添加以下列:

#DF After when i call those functions:
AM_Loca1(DF)#create Auto localisation 1
AM_localoisation2(DF)# create Auto localisation 2
AM_localoisation3(DF)# create Auto localisation 1
AM_WP1(DF)
DF.head()

在此处输入图像描述

我想使用此功能添加“WP Level 2”和“WP Level 2”:

def AM_WP23(df,df_mapping23):
  merge=pd.merge(left=df,
               right=df_mapping23,
               left_on=["Auto localisation 2","Auto localisation 3"],
               right_on=['Localisation level 2 AM','Localisation level 3 AM'],how="left").drop_duplicates()
  df["WP Level 2"]=merge["WP Level 2"]
  df["WP Level 3"]=merge["WP Level 3"]
  return df

df_mapping23 包含以下信息:

df_mapping23.head()

在此处输入图像描述

当我第一次调用这个程序时:

AM_Loca1(DF)
AM_localoisation2(DF)
AM_localoisation3(DF)
AM_WP1(DF)
AM_WP23(DF,df_mapping23)

当我第二次运行它时,我收到此错误消息。我希望我的问题是有道理的......任何帮助都非常感谢!

KeyError                                  Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2897             try:
-> 2898                 return self._engine.get_loc(casted_key)
   2899             except KeyError as err:

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'WP Level 2'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
3 frames
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2898                 return self._engine.get_loc(casted_key)
   2899             except KeyError as err:
-> 2900                 raise KeyError(key) from err
   2901 
   2902         if tolerance is not None:

KeyError: 'WP Level 2'

标签: pythonpandasmerge

解决方案


推荐阅读