gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:26:20 26 4
gpt4 key购买 nike

假设我有两个这样的 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)

关于python - Pandas 中的 join 和 merge 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22676081/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com