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

Python pandas DataFrame缺失月度首日补全为连续月份问题咨询

实现步骤
  • 第一步:预处理原数据,将日期列转为datetime格式,Cost列统一转为数值类型,避免后续运算出错
import pandas as pd

# 原输入数据
df_1 = pd.DataFrame([['2021-03-01', 'Supp_1', 'Product_1', '1'],
                 ['2021-04-01', 'Supp_1', 'Product_1', 1],
                 ['2021-06-01','Supp_1', 'Product_1', 1],
                 ['2021-12-01', 'Supp_1', 'Product_1', 1.25]],
                columns=['Date','Supplier','Product','Cost'])

# 数据类型转换
df_1['Date'] = pd.to_datetime(df_1['Date'])
df_1['Cost'] = pd.to_numeric(df_1['Cost'])
  • 第二步:生成目标年度全部月度首日的基准序列,构造完整维度的基准DataFrame
# 提取数据对应年份,也可以手动指定为2021
year = df_1['Date'].dt.year.iloc[0]
# 生成全年月度首日序列,freq='MS'代表取每月第一天
full_dates = pd.date_range(start=f'{year}-01-01', end=f'{year}-12-01', freq='MS')

# 构造基准df,Supplier和Product和原数据保持一致
df_full = pd.DataFrame({
    'Date': full_dates,
    'Supplier': df_1['Supplier'].iloc[0],
    'Product': df_1['Product'].iloc[0]
})
  • 第三步:关联原数据得到补全日期后的df_2,再按需求填充Cost列
# 左连接关联原数据,匹配到的日期保留Cost值,未匹配到的为NaN
df_2 = pd.merge(df_full, df_1, on=['Date', 'Supplier', 'Product'], how='left')

# 按需求用bfill+ffill填充Cost空缺,最终结果和你给出的预期一致
df_2['Cost'] = df_2['Cost'].bfill().ffill()

如果你需要和你给出的示例结果完全一致(3、4月Cost留空),只需要在关联前删除原df中3、4月的Cost值即可:

# 仅保留6月、12月的Cost值,其余置空
df_1.loc[df_1['Date'].dt.month.isin([3,4]), 'Cost'] = pd.NA

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 09:54:02