合并不同行日期时间:处理含混合格式与NA的Start.Date列
解决日期时间补全问题
我来帮你搞定这个Start.Date列的日期时间补全需求!你的数据里存在日期、时间拆分在不同行,还有NA和其他杂项,需要把对应日期和时间合并成完整的datetime,缺失的行沿用前一行的完整日期时间,下面我用两种常用工具给出解决方案:
方案一:用R语言(tidyverse系列包)
首先我们先模拟你的原始数据,然后一步步处理:
步骤1:加载依赖包并创建模拟数据
library(tidyverse) library(lubridate) # 模拟你的原始数据结构 df <- tibble( Start.Date = c("11/6/2017", "07:00", "3/22/2018", "06:38", "11/6/2017", "c", "07:00", "<NA>", "<NA>", "<NA>", "<NA>", "11/5/2017", "07:00", "3/21/2018", "06:38"), Value = c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o") )
步骤2:处理数据补全日期时间
df_processed <- df %>% # 1. 标记并提取日期、时间到临时列 mutate( temp_date = ifelse(str_detect(Start.Date, "/"), Start.Date, NA), temp_time = ifelse(str_detect(Start.Date, ":"), Start.Date, NA) ) %>% # 2. 前向填充日期,让每个时间行都匹配最近的日期 fill(temp_date, .direction = "down") %>% # 3. 合并日期和时间为完整的datetime对象 mutate( Start.Date = ifelse(!is.na(temp_time), mdy_hm(paste(temp_date, temp_time)), NA) ) %>% # 4. 前向填充完整的datetime,补全后续的NA行 fill(Start.Date, .direction = "down") %>% # 5. 清理临时列 select(-temp_date, -temp_time) # 查看处理后的结果 print(df_processed)
方案二:用Python(Pandas库)
同样先模拟数据,再进行处理:
步骤1:导入库并创建模拟数据
import pandas as pd # 模拟原始数据 data = { 'Start.Date': ["11/6/2017", "07:00", "3/22/2018", "06:38", "11/6/2017", "c", "07:00", None, None, None, None, "11/5/2017", "07:00", "3/21/2018", "06:38"], 'Value': ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o"] } df = pd.DataFrame(data)
步骤2:处理数据补全日期时间
# 1. 提取日期和时间到临时列 df['temp_date'] = df['Start.Date'].where(df['Start.Date'].str.contains('/', na=False)) df['temp_time'] = df['Start.Date'].where(df['Start.Date'].str.contains(':', na=False)) # 2. 前向填充日期,确保每个时间行都有对应的日期 df['temp_date'] = df['temp_date'].ffill() # 3. 合并日期和时间为datetime格式 df['Start.Date'] = pd.to_datetime(df['temp_date'] + ' ' + df['temp_time'], format='%m/%d/%Y %H:%M', errors='coerce') # 4. 前向填充完整的datetime,补全NA行 df['Start.Date'] = df['Start.Date'].ffill() # 5. 删除临时列 df = df.drop(['temp_date', 'temp_time'], axis=1) # 查看结果 print(df)
两种方案最终都会得到你需要的格式:每一行的Start.Date都是完整的日期时间,缺失的行自动沿用前一行的有效日期时间。
内容的提问来源于stack exchange,提问作者Tze
相关产品推荐
相关产品推荐

