如何将用户输入的年月日期与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
相关产品推荐
相关产品推荐

