【发布时间】:2017-06-08 11:28:31
【问题描述】:
我正在尝试使用两列连接两个 pandas 数据框:
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]'
知道什么是正确的方法吗?谢谢!
【问题讨论】:
-
left_on和right_on应该是字符串列表,而不是看起来像列表的字符串。 -
简单的错字:
left_on=['A_c1','c2']而不是'[A_c1,c2]'。正如@root 所说,它需要一个字符串列表。同样right_on = ['B_c1','c2']. -
顺便说一句,将数据框
A_df的列命名为以前缀“A_”开头,并将来自B_df的列命名为B_...是一种不好的做法。这是完全没有必要的,而且它使连接、合并、groupbys 等基本操作变得烦人。
标签: python python-3.x pandas join