You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并两个含相同日期索引的Pandas DataFrame并按时间排序

Pandas合并两个DataFrame并按时间排序的解决方案

需求说明

现有两个以日期为索引的Pandas DataFrame:

  • df1包含「Temperatures」(温度)和「Time」(时间)列
  • df2仅包含「Time」列
    需要将二者合并,保留df2的所有行(对应温度值填充为NaN),最终结果按时间顺序排列。

示例数据

先构建示例中的两个DataFrame:

import pandas as pd
import numpy as np

# 构建df1
data1 = [[78,'6:53','6/15/2023'],[79,'7:53','6/15/2023'],[80,'8:53','6/15/2023']]
df1=pd.DataFrame(data1, columns=['Temperatures','Time','Dates']).set_index('Dates')

# 构建df2
data2 = [['7:51','6/15/2023'],['8:51','6/15/2023']]
df2 = pd.DataFrame(data2, columns=['Time','Dates']).set_index('Dates')

解决步骤

  1. 合并DataFrame
    用pd.concat纵向合并两个DataFrame,缺失的Temperatures列会自动填充为NaN:
combined_df = pd.concat([df1, df2])
  1. 转换时间格式并排序
    将Time列转换为时间类型(避免字符串排序的误差),然后按日期和时间排序:
# 转换Time列为时间类型
combined_df['Time'] = pd.to_datetime(combined_df['Time'], format='%H:%M').dt.time

# 按日期和时间排序,重置索引后恢复日期索引
sorted_df = combined_df.sort_values(by=['Dates', 'Time']).reset_index().set_index('Dates')

最终结果

执行上述代码后,打印sorted_df即可得到期望的结果:

Temperatures      Time
Dates                             
6/15/2023           78.0  06:53:00
6/15/2023            NaN  07:51:00
6/15/2023           79.0  07:53:00
6/15/2023            NaN  08:51:00
6/15/2023           80.0  08:53:00

内容的提问来源于stack exchange,提问作者Tyler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 16:13:14