Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫:意外的连接行为导致NaN_Python_Pandas - Fatal编程技术网

Python 熊猫:意外的连接行为导致NaN

Python 熊猫:意外的连接行为导致NaN,python,pandas,Python,Pandas,我有两个数据帧,我正在尝试加入pandas(版本0.18.1) 然而,当我连接这两个表时,最后一行没有正确连接,因为它是左连接,结果是NaN df = test2.join(test1,on='id_parent',how='left') id_2 id_parent id_1 place 0 6 1 2 Lenawee 1 7 2 3 Montreal 2 8 3

我有两个数据帧,我正在尝试加入pandas(版本0.18.1)

然而,当我连接这两个表时,最后一行没有正确连接,因为它是左连接,结果是NaN

df = test2.join(test1,on='id_parent',how='left')

   id_2  id_parent  id_1      place
0     6          1     2    Lenawee
1     7          2     3   Montreal
2     8          3     4    Berrien
3     9          4     5     Ottawa
4    10          5   NaN        NaN
这对我来说没有意义——id_parent和id_1是连接两个表的键,它们都有相同的值。两列具有相同的数据类型(int64)。这里发生了什么?

连接主要基于索引,用于:

In [18]:
test2.merge(test1,left_on='id_parent', right_on='id')

Out[18]:
   id_2  id_parent  id      place
0     6          1   1       Kent
1     7          2   2    Lenawee
2     8          3   3  Washtenaw
3     9          4   4    Berrien
4    10          5   5     Ottawa
您得到的是
NaN
,因为rhs将使用rhs索引,并且没有
0
5
的条目,所以您得到的
NaN
连接主要是在索引上,用于此:

In [18]:
test2.merge(test1,left_on='id_parent', right_on='id')

Out[18]:
   id_2  id_parent  id      place
0     6          1   1       Kent
1     7          2   2    Lenawee
2     8          3   3  Washtenaw
3     9          4   4    Berrien
4    10          5   5     Ottawa

您得到的是
NaN
,因为rhs将使用rhs索引,并且没有
0
5
的条目,所以您得到的是
NaN

这里我引用了pandas的文档:“join采用可选的on参数,可能是一个列或多个列名,它指定传递的数据帧将在数据帧中的该列上对齐。"


因此,在您的例子中,您正在匹配test1中id_parent上test2的索引。

这里我引用了pandas的文档:“join采用可选的on参数,该参数可以是一个列或多个列名,它指定传递的数据帧与数据帧中的该列对齐。”


因此,在您的例子中,您正在匹配test1中id_父项上test2的索引。

Ah…我认为应该使用.join(),因为在SQL中,我认为这应该是一个连接。哎呀。非常感谢。啊……我想我应该使用.join(),因为在SQL中,我认为这应该是一个连接。哎呀。非常感谢。