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

如何在DataFrame员工查询逻辑中添加同行LeftDate空值判断条件?

问题解决:员工查询中LeftDate为空值的判断修正

你的代码里有两个关键问题导致第二个条件失效:

  • Pandas里判断缺失值不能用== None,得用pd.isna()或者df.isnull()——因为None在pandas的Series里会被处理成NaN,直接用==判断会返回布尔Series,结果不准确。
  • 你现在的写法是检查整个LeftDate列是否为null,而不是输入姓名对应的那一行的LeftDate是否为null,逻辑完全错位了。

修正后的代码如下:

import pandas as pd

while True:
    staffName = input("Please key in a staff's full name: ")
    # 先定位到该员工的行数据
    staff_row = first_df[first_df['Staff'] == staffName]
    if not staff_row.empty:
        # 判断该行的LeftDate是否为缺失值
        if pd.isna(staff_row['LeftDate'].iloc[0]):
            print(f"{staffName} is a current staff of the organization.")
        else:
            print(f"{staffName} was a previous staff of the organization.")
        # 统一处理退出逻辑,避免重复代码
        exit_choice = input("Would you like to key in another staff's full name? (Y/N): ")
        if exit_choice.upper() == 'N':
            print("Thank you for using the organization's staff records system.")
            break
    else:
        print(f"{staffName} is not found in the staff records.")

关键改动说明:

  1. 先通过first_df[first_df['Staff'] == staffName]筛选出对应员工的行,用staff_row.empty判断员工是否存在,比原来的.any()更直观。
  2. 用pd.isna(staff_row['LeftDate'].iloc[0])精准判断目标员工行的LeftDate是否为缺失值,iloc[0]用于提取筛选后行的LeftDate值(假设员工姓名唯一)。
  3. 把退出逻辑统一提取,避免重复编写相同代码,减少冗余。
  4. 用f-string替代字符串拼接,代码更简洁易读。
  5. 对退出输入做upper()处理,兼容小写的'n'输入,提升交互容错性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:45:27