合并两个数据框但忽略带有 NaT 的行

Merge two dataframes but ignore rows with NaT

我想在 '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    |

也许尝试使用三列 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

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