假设我有两个这样的 DataFrame:
left = pd.DataFrame({'key1': ['foo', 'bar'], 'lval': [1, 2]})
right = pd.DataFrame({'key2': ['foo', 'bar'], 'rval': [4, 5]})
我想合并它们,所以我尝试这样的事情:
pd.merge(left, right, left_on='key1', right_on='key2')
我很高兴
key1 lval key2 rval
0 foo 1 foo 4
1 bar 2 bar 5
但我正在尝试使用 join 方法,我一直认为它非常相似。
left.join(right, on=['key1', 'key2'])
我明白了:
//anaconda/lib/python2.7/site-packages/pandas/tools/merge.pyc in _validate_specification(self)
406 if self.right_index:
407 if not ((len(self.left_on) == self.right.index.nlevels)):
--> 408 raise AssertionError()
409 self.right_on = [None] * n
410 elif self.right_on is not None:
AssertionError:
我错过了什么?
最佳答案
pandas.merge()
是用于所有合并/连接行为的底层函数。
DataFrames 提供 pandas.DataFrame.merge()
和 pandas.DataFrame.join()
方法作为访问 pandas 功能的便捷方式。合并()
。例如,df1.merge(right=df2, ...)
等价于 pandas.merge(left=df1, right=df2, ...)
。
这些是 df.join()
和 df.merge()
之间的主要区别:
df1.join(df2)
总是通过 df2
的索引加入,但 df1.merge(df2)
可以连接到 df2
的一列或多列(默认)或 df2
的索引(使用 right_index=True
)。 df1.join(df2)
使用df1
和df1.merge(df2)
的索引使用 df1
的列。这可以通过指定 df1.join(df2, on=key_or_keys)
或 df1.merge(df2, left_index=True)
来覆盖。 df1.join(df2)
默认进行左连接(保留 df1
的所有行),但 df.merge
默认执行内连接(仅返回匹配的 df1
和 df2
行)。所以,通用的方法是使用 pandas.merge(df1, df2)
或 df1.merge(df2)
。但是对于一些常见情况(保留所有 df1
行并加入 df2
中的索引),您可以使用 df1.join( df2)
代替。
http://pandas.pydata.org/pandas-docs/stable/merging.html#database-style-dataframe-joining-merging 上的文档中有关这些问题的一些说明:
merge
is a function in the pandas namespace, and it is also available as a DataFrame instance method, with the calling DataFrame being implicitly considered the left object in the join.The related
DataFrame.join
method, usesmerge
internally for the index-on-index and index-on-column(s) joins, but joins on indexes by default rather than trying to join on common columns (the default behavior formerge
). If you are joining on index, you may wish to useDataFrame.join
to save yourself some typing.
...
These two function calls are completely equivalent:
left.join(right, on=key_or_keys) pd.merge(left, right, left_on=key_or_keys, right_index=True, how='left', sort=False)
https://stackoverflow.com/questions/22676081/