如果我尝试这个(有两个不同的pandas
年份,一个在Python 2中,另一个在Python 3中)
import pandas as pd
x = pd.DataFrame({"id": [1, 2,3], "value1": [5,5,5]})
y = pd.DataFrame({"id": [1], "value2": [10]})
z1 = x.join(y, on = "id")
z2 = x.join(y, on = "id", lsuffix = "_left", rsuffix = "_right")
z3 = x.join(y, lsuffix = "_left", rsuffix = "_right")
第一个连接失败了ValueError
,第二个没有破坏但y
不匹配,只有第三个连接产生预期结果,即y
的行匹配到x
。
join
的文件说
on:名称,元组/名称列表,或者类似于数组的列或索引级别名称,用于连接其他索引,否则加入index-on-index。如果给定多个值,则另一个DataFrame必须具有MultiIndex。如果数组尚未包含在调用DataFrame中,则可以将数组作为连接键传递。像Excel VLOOKUP操作一样。
这是(即z2
会发生什么)一个错误,还是以某种方式有意义?
df.join(...)
通常用于连接df
的索引和另一个DataFrame的索引。
df.join(..., on='id')
将id
的df
列与另一个DataFrame的索引连接起来。 Per the docs(我的重点):
on:name,tuple / names of list或array-like
调用者中的列或索引级别名称,以加入其他索引,否则加入index-on-index。如果给定多个值,则另一个DataFrame必须具有MultiIndex。如果数组尚未包含在调用DataFrame中,则可以将数组作为连接键传递。像Excel VLOOKUP操作一样
由于x
和y
看起来像这样:
In [14]: x
Out[14]:
id value1
0 1 5
1 2 5
2 3 5
In [15]: y
Out[15]:
id value2
0 1 10
x.join(y, on='id')
试图加入x['id']
(价值1, 2, 3
)与y.index
(价值0
)。由于x['id']
和y.index
没有共同的值,因此(默认情况下)左连接为连接生成的新y
列中的值生成NaN。
z1 = x.join(y, on = "id")
加注
ValueError: columns overlap but no suffix specified: Index(['id'], dtype='object')
因为连接产生的y
列包括id
,它已经是x
列名。当列名重叠时,必须指定lsuffix
,rsuffix
或两者以消除列名称的歧义。
z2 = x.join(y, on = "id", lsuffix = "_left", rsuffix = "_right")
回归
In [12]: z2
Out[12]:
id_left value1 id_right value2
0 1 5 NaN NaN
1 2 5 NaN NaN
2 3 5 NaN NaN
因为常见的x
和y
-column(即id
列)已被消除歧义。 NaN
值是由于x['id']
和y.index
没有共同的值(如上所述)。
z3 = x.join(y, lsuffix = "_left", rsuffix = "_right")
生产
In [20]: z3
Out[20]:
id_left value1 id_right value2
0 1 5 1.0 10.0
1 2 5 NaN NaN
2 3 5 NaN NaN
因为现在正在x.index
和y.index
上进行连接。