python - 使用多个数据框合并左侧
问题描述
如果不清楚,我会尝试解释我的问题,请原谅。我有这个数据源,我创建了三个函数来合并两个数据框。我的源代码的前五行:
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'
解决方案
推荐阅读
- docker - GitLab CI docker 构建失败
- html - 在 Github Pages 我的网站不显示照片
- excel - 将空白单元格返回为空白而不是 0 的索引公式
- string - 我如何在 unity2d 中消除这个讨厌的错误?
- java - 如何在自定义 JComponent 中正确实现 MouseInputListener
- jenkins - groovy.lang.MissingPropertyException:没有这样的属性:类的道具:groovy.lang.Binding
- concurrency - 无法识别死锁
- python - 如何将数据帧从长转换为宽,索引中的值按年份分组?
- stripe-payments - 在 Stripe 之外开具发票时,使用什么 Stripe webhook 来捕获订阅续订?
- laravel - Yajra Laravel Datatable 列排序和搜索在服务器端模式下不起作用