熊猫加入(合并?)数据框,仅保留唯一索引

时间:2019-02-24 14:16:21

标签: pandas dataframe join merge

我有一个带有日期索引的数据框。有些日期以某种方式丢失了。我将其称为数据框A。我还有另一个数据框,其中包含有关日期。我将其称为B

我想合并两个数据框:

保留A的所有索引并与B一起加入,但是我不希望B中的任何与{{1}共享索引的行} 。也就是说,我只希望A返回的A缺少的行。

这最容易实现吗?

注意:

这种行为对于我拥有的数据库是正确的。我会做大约400次。

3 个答案:

答案 0 :(得分:3)

如果我正确阅读了问题,那么您想要的是

B[~B.index.isin(A.index)]

例如:

In [192]: A
Out[192]:
Empty DataFrame
Columns: []
Index: [1, 2, 4, 5]

In [193]: B
Out[193]:
Empty DataFrame
Columns: []
Index: [1, 2, 3, 4, 5]

In [194]: B[~B.index.isin(A.index)]
Out[194]:
Empty DataFrame
Columns: []
Index: [3]

要使用A中的数据,否则从B中获取数据,则可以

pd.concat([A, B[~B.index.isin(A.index)]).sort_index()

或者,假设A不包含要保留的空元素,则可以采用其他方法,并采用类似的方法

pd.DataFrame(A, index=B.index).fillna(B)

答案 1 :(得分:2)

我相信您需要Index.difference

B.loc[B.index.difference(A.index)]

编辑:

A = pd.DataFrame({'A':range(10)}, index=pd.date_range('2019-02-01', periods=10))
B = pd.DataFrame({'A':range(10, 20)}, index=pd.date_range('2019-01-27', periods=10))

df = pd.concat([A, B.loc[B.index.difference(A.index)]]).sort_index()
print (df)
             A
2019-01-27  10
2019-01-28  11
2019-01-29  12
2019-01-30  13
2019-01-31  14
2019-02-01   0
2019-02-02   1
2019-02-03   2
2019-02-04   3
2019-02-05   4
2019-02-06   5
2019-02-07   6
2019-02-08   7
2019-02-09   8
2019-02-10   9

df1= pd.concat([A, B])
df1 = df1[~df1.index.duplicated()].sort_index()
print (df1)
             A
2019-01-27  10
2019-01-28  11
2019-01-29  12
2019-01-30  13
2019-01-31  14
2019-02-01   0
2019-02-02   1
2019-02-03   2
2019-02-04   3
2019-02-05   4
2019-02-06   5
2019-02-07   6
2019-02-08   7
2019-02-09   8
2019-02-10   9

答案 2 :(得分:2)

虽然已经有很多答案了,但我想分享它,因为它太短了

pd.concat([A, B]).drop_duplicates(keep='first')
相关问题