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

Python中如何根据月份修正DataFrame日期列的年份值

问题描述

现有名为weather的数据集,其中Date列所有日期的年份均为2020,但实际需要包含2020、2021、2022三个年份。更新规则为:每次出现01月时年份递增(每年最后一个月不一定是12月,新年从01月开始)。

当前Date列示例:

Date
2020-01-01
2020-01-02
...
2020-01-01

期望的Date列示例:

Date
2020-01-01
2020-01-02
...
2021-01-01
...
2022-01-01

原代码问题分析

你提供的代码存在多处逻辑错误:

  • 定义的month列表未被使用,属于冗余代码
  • 嵌套循环无意义,外层遍历每行的同时内层遍历月份列表,重复执行判断
  • year变量固定为2022,未根据01月的出现动态更新年份
  • 对单个字符串元素调用apply方法(apply是DataFrame/Series的方法,单个字符串无法使用)
  • 字符串拼接错误,直接使用字符串'year'而非动态年份值
修正方案

推荐两种实现方式,优先选择向量化操作(效率更高,适合大数据集):

方法一:Pandas向量化操作(推荐)

利用Pandas的向量化方法替代循环,处理效率更高:

import pandas as pd

# 确保Date列为字符串类型(若原本是datetime类型,先转换为字符串)
weather['Date'] = weather['Date'].astype(str)

# 提取月份信息
weather['month'] = weather['Date'].str[5:7]

# 计算年份增量:统计累计出现01月的次数,减1后得到需要递增的年份数
weather['year_increment'] = (weather['month'] == '01').cumsum() - 1

# 计算新年份并拼接成新的日期字符串
weather['Date'] = (2020 + weather['year_increment']).astype(str) + weather['Date'].str[4:]

# 删除临时生成的中间列(可选)
weather.drop(['month', 'year_increment'], axis=1, inplace=True)

方法二:迭代遍历(适合理解逻辑)

如果需要更直观的逻辑展示,可以使用迭代方式处理:

current_year = 2020
jan_count = 0

for idx, date_str in enumerate(weather['Date']):
    month = date_str[5:7]
    if month == '01':
        jan_count += 1
        # 第一次出现01月时保持2020,后续每出现一次递增1年
        current_year = 2020 + (jan_count - 1)
    # 拼接新的日期字符串
    weather.loc[idx, 'Date'] = f"{current_year}{date_str[4:]}"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:15:24