pandas :合并(加入)多列上的两个数据框 [英] pandas: merge (join) two data frames on multiple columns
问题描述
我正在尝试使用两列连接两个熊猫数据框:
I am trying to join two pandas data frames using two columns:
new_df = pd.merge(A_df, B_df, how='left', left_on='[A_c1,c2]', right_on = '[B_c1,c2]')
但得到以下错误:
pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4164)()
pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4028)()
pandas/src/hashtable_class_helper.pxi in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:13166)()
pandas/src/hashtable_class_helper.pxi in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:13120)()
KeyError: '[B_1, c2]'
知道这样做的正确方法是什么吗?谢谢!
Any idea what should be the right way to do this? Thanks!
推荐答案
试试这个
new_df = pd.merge(A_df, B_df, how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html
left_on : 标签或列表,或在左边加入的类似数组的字段名称数据帧.可以是长度为 的向量或向量列表DataFrame 使用特定向量作为连接键而不是列
left_on : label or list, or array-like Field names to join on in left DataFrame. Can be a vector or list of vectors of the length of the DataFrame to use a particular vector as the join key instead of columns
right_on :要加入的标签或列表,或类似数组的字段名称在每个 left_on 文档的右侧 DataFrame 或矢量/矢量列表中
right_on : label or list, or array-like Field names to join on in right DataFrame or vector/list of vectors per left_on docs
这篇关于 pandas :合并(加入)多列上的两个数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!