熊猫“加入”古怪

问题描述 投票:2回答:1

如果我尝试这个(有两个不同的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会发生什么)一个错误,还是以某种方式有意义?

python pandas join merge
1个回答
2
投票

df.join(...)通常用于连接df的索引和另一个DataFrame的索引。

df.join(..., on='id')iddf列与另一个DataFrame的索引连接起来。 Per the docs(我的重点):

on:name,tuple / names of list或array-like

调用者中的列或索引级别名称,以加入其他索引,否则加入index-on-index。如果给定多个值,则另一个DataFrame必须具有MultiIndex。如果数组尚未包含在调用DataFrame中,则可以将数组作为连接键传递。像Excel VLOOKUP操作一样

由于xy看起来像这样:

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列名。当列名重叠时,必须指定lsuffixrsuffix或两者以消除列名称的歧义。


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

因为常见的xy-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.indexy.index上进行连接。

© www.soinside.com 2019 - 2024. All rights reserved.