R语言日期格式化:宽格式降雪数据转为年月单列长格式求助
宽格式降雪数据转长格式实现方案
以下分别提供R语言tidyverse生态和Python pandas生态的实现代码,适配你的雪季统计规则:
R语言实现方案
library(tidyverse) # 预定义月份映射规则:1-6月归属雪季标注的后一年,7-12月归属雪季标注的前一年 month_rule <- tibble( month_abb = c("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"), month_num = 1:12, is_next_year = c(rep(TRUE,6), rep(FALSE,6)) ) # 宽转长处理逻辑 snow_long <- snow_wide %>% # 保留雪季和总降雪量列,其余月份列转长 pivot_longer(cols = -c(SEASON, TOTAL), names_to = "month_abb", values_to = "monthly_snowfall") %>% left_join(month_rule, by = "month_abb") %>% # 拆分雪季年份计算对应年月 mutate(season_start = as.numeric(substr(SEASON, 1, 4)), cal_year = ifelse(is_next_year, season_start + 1, season_start), year_month = paste0(cal_year, "-", str_pad(month_num, 2, side = "left", pad = "0"))) %>% # 按需调整输出列顺序 select(SEASON, year_month, monthly_snowfall, TOTAL)
转换后输出示例:
| SEASON | year_month | monthly_snowfall | TOTAL |
|---|---|---|---|
| 1869-70 | 1869-12 | 5.3 | 27.8 |
| 1869-70 | 1870-01 | 1.1 | 27.8 |
Python pandas实现方案
import pandas as pd import numpy as np # 预定义月份映射规则 month_map = { "JAN": (1, True), "FEB": (2, True), "MAR": (3, True), "APR": (4, True), "MAY": (5, True), "JUN": (6, True), "JUL": (7, False), "AUG": (8, False), "SEP": (9, False), "OCT": (10, False), "NOV": (11, False), "DEC": (12, False) } # 宽转长处理 snow_long = snow_wide.melt( id_vars=["SEASON", "TOTAL"], var_name="month_abb", value_name="monthly_snowfall" ) # 生成年月字段 snow_long[["month_num", "is_next_year"]] = snow_long["month_abb"].apply(lambda x: pd.Series(month_map[x])) snow_long["season_start"] = snow_long["SEASON"].str[:4].astype(int) snow_long["cal_year"] = np.where(snow_long["is_next_year"], snow_long["season_start"] + 1, snow_long["season_start"]) snow_long["year_month"] = snow_long["cal_year"].astype(str) + "-" + snow_long["month_num"].astype(str).str.zfill(2) # 调整输出列 snow_long = snow_long[["SEASON", "year_month", "monthly_snowfall", "TOTAL"]]
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

