【问题标题】:Merge two dataframes but ignore rows with NaT合并两个数据框但忽略带有 NaT 的行
【发布时间】:2021-10-24 07:07:58
【问题描述】:

我有两个要在“ID”和“updated_date”上合并的数据框。它们之间的唯一区别是 df1 中的 'other_date' 列包含一对 NaT,而 df2 包含一个 'type' 列。

我希望生成的 df 对所有最初包含 NaT 的合并行(第 3 行)具有 NaN

    ID   |  updated_date |  other_date | 
0   11   |   2019-04-03  |  2019-04-09 | 
1   11   |   2019-05-02  |  2019-05-14 |
2   11   |   2019-05-20  |  2019-06-05 | 
3   11   |   2019-03-03  |      NaT    |

    ID   |  updated_date |  other_date |   type   |
0   11   |   2019-04-03  |  2019-04-09 |    C     |
1   11   |   2019-05-02  |  2019-05-14 |    C     |
2   11   |   2019-05-20  |  2019-06-05 |    D     |
3   11   |   2019-03-03  |  2019-03-04 |    C     |

期望的输出:

    ID   |  updated_date |  other_date |   type   |
0   11   |   2019-04-03  |  2019-04-09 |    C     |
1   11   |   2019-05-02  |  2019-05-14 |    C     |
2   11   |   2019-05-20  |  2019-06-05 |    D     |
3   11   |   2019-03-03  |      NaT    |   NaN    |

【问题讨论】:

    标签: python pandas dataframe numpy merge


    【解决方案1】:

    也许尝试使用三列 ID、updated_date 和 other_date 进行左连接?

    df1.merge(df2, how = "left", on = ["ID", "updated_date", "other_date"])
    

    输出

    ID updated_date other_date type
    0 11 2019-04-03 2019-04-09 C
    1 11 2019-05-02 2019-05-14 C
    2 11 2019-05-20 2019-06-05 D
    3 11 2019-03-03 NaT NaN

    【讨论】:

      【解决方案2】:

      使用include(column) 和附加函数,这将帮助您使列表相似,然后在最后一个单元格中使用if(condition ) 打印NaN

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-30
        • 1970-01-01
        • 2021-12-18
        • 2017-01-06
        • 2017-09-14
        • 2015-04-18
        • 1970-01-01
        相关资源
        最近更新 更多