首页 > 解决方案 > 附加 2 个带有行和列子集的 pandas 数据帧

问题描述

我有2个这样的数据框

df = pd.DataFrame({"date":["2019-01-01", "2019-01-02", "2019-01-03", "2019-01-04"],
                   "A": [1., 2., 3., 4.],
                   "B": ["a", "b", "c", "d"]})
df["date"] = pd.to_datetime(df["date"])

df_new = pd.DataFrame({"date":["2019-01-02", "2019-01-03", "2019-01-04", "2019-01-05", "2019-01-06"],
                       "A": [2, 3.5, 4, 5., 6.],
                       "B": ["b", "c1", "d", "e", "f"]})
df_new["date"] = pd.to_datetime(df_new["date"])

所以,我的数据框看起来像这样

df
-----------------------
date            A    B
2019-01-01      1    a
2019-01-02      2    b
2019-01-03      3    c
2019-01-04      4    d

df_new
----------------------
date            A    B
2019-01-02      2    b
2019-01-03      3.5  c1
2019-01-04      4    d
2019-01-05      5    e
2019-01-06      6    f

从这些数据帧中,我想将 df 附加到具有特定条件的 df_new 如下:

  1. 在两个数据框中都有可用日期的任何行,我们在 df_new 中采用这些行

  2. 任何日期在 df 中可用但在 df_new 中不可用的行,我们在 df 中取这些行

最后我的预期输出看起来像这样

Expected output
----------------------
date            A    B
2019-01-01      1    a      (take from df)
2019-01-02      2    b      (take from df_new)
2019-01-03      3.5  c1     (take from df_new)
2019-01-04      4    d      (take from df_new)
2019-01-05      5    e      (take from df_new)
2019-01-06      6    f      (take from df_new)

我可以考虑找到 2 个数据框之间的行差异,但是当我考虑到日期列时它不起作用。我可以有你的建议吗?谢谢你。

标签: pythonpandas

解决方案


按按列使用concat和删除重复项,最后按按创建默认唯一索引值:dateDataFrame.drop_duplicatesDataFrame.reset_index

df = pd.concat([df, df_new]).drop_duplicates('date', keep='last').reset_index(drop=True)
print (df)
        date    A   B
0 2019-01-01  1.0   a
1 2019-01-02  2.0   b
2 2019-01-03  3.5  c1
3 2019-01-04  4.0   d
4 2019-01-05  5.0   e
5 2019-01-06  6.0   f

推荐阅读