对比两个字典并筛选:保留字典2中大于字典1的对应时间戳
解决方案
可以用字典推导式结合列表推导快速实现需求,代码如下:
# 前提:dictionary1和dictionary2已定义,且Timestamp为pandas的时间戳类型 filtered_dict = { key: [ts for ts in dictionary2[key] if ts > dictionary1[key]] for key in dictionary1 }
逻辑说明
- 遍历
dictionary1的每个键,确保覆盖所有需要处理的键(A、L、S、D) - 对
dictionary2中当前键对应的时间戳列表做过滤:只保留比dictionary1对应键的时间戳更大的元素 - 最终生成符合要求的新字典
验证结果
运行上述代码后,得到的结果与期望完全一致:
{'A': [Timestamp('2023-01-10 00:00:00')], 'L': [Timestamp('2023-01-16 00:00:00'), Timestamp('2023-01-13 00:00:00'), Timestamp('2023-01-12 00:00:00')], 'S': [Timestamp('2022-01-13 00:00:00'), Timestamp('2023-01-12 00:00:00')], 'D': [Timestamp('2023-01-16 00:00:00'), Timestamp('2022-10-18 00:00:00')]}
内容的提问来源于stack exchange,提问作者realpcy
相关产品推荐
相关产品推荐

