如何筛选DataFrame中last_name以S开头的员工并打印姓名
问题描述
我有一个名为employees.csv的CSV文件,已将其转换为名为Employees Filtered的DataFrame,目标是找出所有last_name以字母“S”开头的员工并打印结果。
CSV数据如下:
employee_id first_name last_name email department_id favorite_food birthday 1 1 Richard Sanchez rsanchez@yahoo.com 1 Cheese 9/20/1965 2 2 Jon Snow jsnow@yahoo.com 1 Cheese 9/20/1988 3 3 Michael Scott mscott@yahoo.com 3 Sinigang 9/20/2001 4 4 Leslie Knope lknope.yahoo.com@gmail.com 2 UNKNOWN 9/20/2014
我原本使用的代码:
employees_4_1 = pd.DataFrame([employees_merged['last_name'].str.startswith('S')]) print(employees_4_1)
得到的结果:
last_name True True True False
我不需要这些布尔值,而是希望打印出last_name以字母“S”开头的员工姓名。
解决方案
用布尔索引直接过滤整个DataFrame即可,代码如下:
# 若未读取CSV,先执行这步(CSV为空格分隔,用sep='\s+'处理) import pandas as pd employees_merged = pd.read_csv('employees.csv', sep='\s+') # 生成判断条件的布尔掩码 mask = employees_merged['last_name'].str.startswith('S') # 筛选出符合条件的员工数据 filtered_employees = employees_merged[mask] # 打印员工姓名(如需完整信息,直接打印filtered_employees即可) print(filtered_employees[['first_name', 'last_name']])
代码说明
employees_merged['last_name'].str.startswith('S'):生成布尔序列,标记每行的last_name是否以“S”开头。employees_merged[mask]:通过布尔掩码直接筛选出符合条件的整行数据,而非仅保留布尔值。filtered_employees[['first_name', 'last_name']]:提取姓名列打印,按需选择输出内容范围。
预期输出
first_name last_name 0 Richard Sanchez 1 Jon Snow 2 Michael Scott
内容的提问来源于stack exchange,提问作者ProgammerProgammingPrograms
相关产品推荐
相关产品推荐

