python - Pandas 中的 join 和 merge 有什么区别?

假设我有两个这样的 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() 之间的主要区别:

  1. 在右表上查找:df1.join(df2) 总是通过 df2 的索引加入,但 df1.merge(df2)可以连接到 df2 的一列或多列(默认)或 df2 的索引(使用 right_index=True)。
  2. 左表查找:默认情况下,df1.join(df2)使用df1df1.merge(df2)的索引使用 df1 的列。这可以通过指定 df1.join(df2, on=key_or_keys)df1.merge(df2, left_index=True) 来覆盖。
  3. 左与内连接:df1.join(df2) 默认进行左连接(保留 df1 的所有行),但 df.merge 默认执行内连接(仅返回匹配的 df1df2 行)。

所以,通用的方法是使用 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, uses merge 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 for merge). If you are joining on index, you may wish to use DataFrame.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/

相关文章:

python - 列表列表到 numpy 数组中

linux - 在 Bash 脚本中引发错误

regex - 更改文件夹中的所有匹配项

python - 使用 csv 模块从 csv 文件中读取特定列?

linux - 如何 cat <> 包含代码的文件?

python - Python中有标签/转到吗?

linux - 使用 bash 脚本自动化远程登录 session

python - 什么是好的速率限制算法?

linux - bash - 如何将结果从 which 命令传送到 cd

python - 如何通过 Django 发送电子邮件?