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

如何在Pandas DataFrame中不存在指定日期时插入含NA值的记录?

问题

现有一个Pandas DataFrame,需求如下:
当输入日期InputDate="5/1/2022"不存在于Invoice Date列的记录中时,插入一条以该日期为Invoice Date、其余列值为NA的新记录;若该日期已存在,则不执行任何操作。

输入示例:

Invoice Date  ...       Check
1    2022-04-01  ...        1.30
2    2022-03-01  ...        1.19

输出示例:

Invoice Date  ...       Check
0    2022-05-01  ...        NaN
1    2022-04-01  ...        1.30
2    2022-03-01  ...        1.19

解决方案

直接按以下逻辑实现即可:

  1. 统一日期格式,避免因格式差异导致判断错误;
  2. 检查目标日期是否已存在于Invoice Date列;
  3. 若不存在,构造一条对应日期、其余列全为缺失值的记录,插入到DataFrame中。

完整代码示例

import pandas as pd

# 初始化示例DataFrame
df = pd.DataFrame({
    'Invoice Date': ['2022-04-01', '2022-03-01'],
    'Check': [1.30, 1.19]
})

# 处理输入日期,统一转为YYYY-MM-DD格式
target_date = pd.to_datetime("5/1/2022").strftime('%Y-%m-%d')
# 同步转换DataFrame中的日期列格式
df['Invoice Date'] = df['Invoice Date'].apply(lambda x: pd.to_datetime(x).strftime('%Y-%m-%d'))

# 检查日期是否存在
if target_date not in df['Invoice Date'].values:
    # 构造新记录,匹配原DataFrame的所有列
    new_record = pd.DataFrame({
        col: [target_date] if col == 'Invoice Date' else [pd.NA] 
        for col in df.columns
    })
    # 合并新记录与原DataFrame,重置索引
    df = pd.concat([new_record, df], ignore_index=True)

print(df)

代码说明

  • 先统一日期格式是关键,不然像5/1/2022和2022-05-01这种写法会被判定为不同值;
  • 用字典推导式构造新记录,能自动匹配原DataFrame的所有列,不用手动列写每一列;
  • 使用pd.concat合并后重置索引,避免出现索引重复或混乱的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 10:36:21