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

如何编写函数批量将Pandas DataFrame指定列日期转为月初

可行,以下是实现方案

当然可以实现批量处理的自定义函数,下面是具体的代码示例:

首先确保导入所需依赖:

import pandas as pd
from pandas.tseries.offsets import MonthBegin

然后编写自定义函数:

def convert_to_month_start(df, date_columns, suffix='_month_start', overwrite=False):
    # 遍历指定的日期列
    for col in date_columns:
        # 检查列是否存在于DataFrame中
        if col not in df.columns:
            print(f"警告:列 {col} 不存在,已跳过")
            continue
        
        # 将列转换为datetime类型(适配日-月-年的格式)
        df[col] = pd.to_datetime(df[col], dayfirst=True)
        
        # 计算月初日期,沿用你提供的逻辑
        month_start_dates = df[col] - MonthBegin(1)
        
        # 根据参数决定覆盖原列或生成新列
        if overwrite:
            df[col] = month_start_dates.dt.strftime('%d-%m-%y')
        else:
            new_col_name = f"{col}{suffix}"
            df[new_col_name] = month_start_dates.dt.strftime('%d-%m-%y')
    
    return df

用法示例

假设你的DataFrame df 包含 date、order_date 两个日期列,调用方式如下:

# 生成带后缀的新列,保留原日期列
df = convert_to_month_start(df, date_columns=['date', 'order_date'])

# 如果需要直接覆盖原列,设置overwrite=True
df = convert_to_month_start(df, date_columns=['date'], overwrite=True)

关键细节说明

  • dayfirst=True:适配你提供的dd-mm-yyyy日期格式,避免datetime转换时出现格式识别错误
  • dt.strftime('%d-%m-%y'):将计算后的月初日期转为你需要的01-05-24格式
  • 函数会自动跳过不存在的列,并给出提示,避免报错中断流程

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 14:55:03