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

如何将用户输入的年月日期与Pandas DataFrame日期列匹配并提取对应值

匹配月-年日期并提取Pandas DataFrame对应值

完整实现代码

import pandas as pd

# 获取用户输入的月-年日期
birthDate = input("birth year-month? ")
deathDate = input("death year-month? ")

# 示例DataFrame(实际场景可替换为读取CSV/Excel等外部数据)
df = pd.DataFrame({'date': ['1-2022', '2-2022', '3-2022'],
                   'value': [1.4, 1223.22, 2323.23]})

# 定义函数提取对应值,处理日期不存在的情况
def extract_target_value(date_str):
    matched_values = df.loc[df['date'] == date_str, 'value']
    return matched_values.values[0] if not matched_values.empty else None

# 获取并输出结果
birth_value = extract_target_value(birthDate)
death_value = extract_target_value(deathDate)

print(f"birth day value is {birth_value}" if birth_value is not None else f"birth date {birthDate} not found")
print(f"death day value is {death_value}" if death_value is not None else f"death date {deathDate} not found")

代码说明

  • 输入处理:直接通过input()获取用户输入的月-年格式字符串(如2-2022)。
  • 精确匹配:利用df.loc[]按date列的字符串精确匹配筛选目标行,提取对应value值。
  • 容错处理:通过自定义函数判断匹配结果是否为空,避免因输入日期不存在触发索引错误,同时给出清晰提示。

示例运行

当用户输入2-2022和3-2022时,输出:

birth day value is 1223.22
death day value is 2323.23

若输入不存在的日期(如4-2022),则输出:

birth date 4-2022 not found
death day value is 2323.23

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:50:27