Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.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 熊猫:两个数据帧的组合_Python_Pandas - Fatal编程技术网

Python 熊猫:两个数据帧的组合

Python 熊猫:两个数据帧的组合,python,pandas,Python,Pandas,我有两个数据帧,old和new。两者都有相同的列 我想,根据索引 在new中存在但不在old中的old中添加行 使用new中的数据更新old中的行 在pandas中是否有任何有效的方法?我发现,这正是第二步。但是,它不会添加行。我可以在索引上使用一些集合逻辑来完成第一步。然而,这似乎并不有效。做这两个手术最好的方法是什么 例子 old a b 0 1 1 1 3 3 new a b 1 1 2 2 1 2 结果 a b

我有两个数据帧,
old
new
。两者都有相同的列

我想,根据索引

  • new
    中存在但不在
    old
    中的
    old
    中添加行
  • 使用
    new
    中的数据更新
    old
    中的行
pandas
中是否有任何有效的方法?我发现,这正是第二步。但是,它不会添加行。我可以在索引上使用一些集合逻辑来完成第一步。然而,这似乎并不有效。做这两个手术最好的方法是什么

例子
old

    a   b
0   1   1
1   3   3
new

    a   b
1   1   2
2   1   2
结果

    a   b
0   1   1
1   1   2
2   1   2

可以使用
df.reindex()
方法执行第一步

old = old.reindex(index=new.index)

您可以首先为两个数据帧找到公共索引,然后为第一个数据帧找到索引并为第二个数据帧赋值。然后,您将得到以下结果:

In [35]: df1
Out[35]:
   a  b
0  1  1
1  3  3

In [36]: df2
Out[36]:
   a  b
1  1  2
2  1  2

idx = df1.index & df2.index
df1.loc[idx, :] = df2.loc[idx, :]
df1 = df1.combine_first(df2)

In [39]: df1
Out[39]:
   a  b
0  1  1
1  1  2
2  1  2