pandas:合并(联接)多列上的两个数据帧

2024-04-23 10:19:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图使用两列连接两个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]'

你知道怎么做才是正确的吗?谢谢!


Tags: insrcpandasdfgetindexonleft
3条回答

另一种方法是: new_df = A_df.merge(B_df, left_on=['A_c1','c2'], right_on = ['B_c1','c2'], how='left')

这里的问题是,通过使用撇号,您将要传递的值设置为一个字符串,而实际上,正如文档中@Shijo所述,函数需要的是一个标签或列表,而不是一个字符串!如果列表包含为左数据框和右数据框传递的列的每个名称,则每个列名必须在撇号内。根据所述,我们可以理解为什么这是不正确的:

new_df = pd.merge(A_df, B_df,  how='left', left_on='[A_c1,c2]', right_on = '[B_c1,c2]')

这是使用函数的正确方法:

new_df = pd.merge(A_df, B_df,  how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])

试试这个

new_df = pd.merge(A_df, B_df,  how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])

http://pandas.pydata.org/pandas-docs/version/0.19.1/generated/pandas.DataFrame.merge.html

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 : label or list, or array-like Field names to join on in right DataFrame or vector/list of vectors per left_on docs

相关问题 更多 >