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

为含多日期条目的DataFrame填充缺失日期

填充DataFrame缺失日期并补全各颜色的quantity值

方法一:使用reindex结合多级索引

先将date列转为datetime类型,生成完整日期序列与所有颜色的组合,再通过重新索引填充缺失值:

import pandas as pd

# 构造原始DataFrame
df = pd.DataFrame({
    'date': ['2022-07-01', '2022-07-01', '2022-07-01',
             '2022-07-03', '2022-07-03', '2022-07-03',
             '2022-07-04', '2022-07-04', '2022-07-04',
             '2022-07-07', '2022-07-07', '2022-07-07'],
    'color': ['blue', 'red', 'yellow']*4,
    'quantity': [2,1,0,0,3,1,1,0,2,2,1,0]
})

# 转换日期列为datetime格式
df['date'] = pd.to_datetime(df['date'])

# 获取唯一颜色列表与完整日期序列
unique_colors = df['color'].unique()
full_dates = pd.date_range(start=df['date'].min(), end=df['date'].max(), freq='D')

# 创建包含所有(date, color)组合的多级索引
full_index = pd.MultiIndex.from_product([full_dates, unique_colors], names=['date', 'color'])

# 重新索引并填充缺失值为0
df.set_index(['date', 'color'], inplace=True)
df_filled = df.reindex(full_index, fill_value=0).reset_index()

方法二:使用merge实现笛卡尔积合并

通过交叉合并生成所有日期-颜色组合,再与原DataFrame合并填充缺失值:

import pandas as pd

# 构造原始DataFrame(同方法一)
df = pd.DataFrame({
    'date': ['2022-07-01', '2022-07-01', '2022-07-01',
             '2022-07-03', '2022-07-03', '2022-07-03',
             '2022-07-04', '2022-07-04', '2022-07-04',
             '2022-07-07', '2022-07-07', '2022-07-07'],
    'color': ['blue', 'red', 'yellow']*4,
    'quantity': [2,1,0,0,3,1,1,0,2,2,1,0]
})

df['date'] = pd.to_datetime(df['date'])
unique_colors = df['color'].unique()
full_dates = pd.date_range(start=df['date'].min(), end=df['date'].max(), freq='D')

# 生成完整日期和颜色的笛卡尔积组合
full_date_df = pd.DataFrame({'date': full_dates})
color_df = pd.DataFrame({'color': unique_colors})
full_comb = full_date_df.merge(color_df, how='cross')

# 合并原数据并填充缺失值
df_filled = full_comb.merge(df, on=['date', 'color'], how='left').fillna({'quantity': 0})
# 可选:将quantity转为整数类型
df_filled['quantity'] = df_filled['quantity'].astype(int)

两种方法最终都会得到包含所有缺失日期的DataFrame,每个颜色在缺失日期的quantity值均为0。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 06:54:06