Python pandas:用for循环筛选体重≤150患者时遇类型错误求解决
问题分析与解决
错误原因
- 函数中
outcome参数默认值是字符串'Weight',直接拿它和整数150比较,导致str与int无法进行<=运算的类型错误。 - 循环遍历
df[['Patient', 'Weight']]时,实际遍历的是列名('Patient'、'Weight'),而非每一行的患者体重数据,逻辑完全错误。 - 期望输出不符合数据实际:根据提供的DataFrame,体重≤150的患者是Bob、Phil、Jessica,Rob(200)和John(184)体重都超过150。
正确实现(符合for循环要求)
import pandas as pd # 构造DataFrame Patients = [('Rob', 200, 100), ('Bob', 150, 150), ('John', 184, 102), ('Phil', 120, 200), ('Jessica', 100, 143 ) ] df = pd.DataFrame(Patients, columns =['Patient', 'Weight', 'LDL'], index =['0','1', '2', '3', '4']) def get_patients_under_150(df, col='Weight'): result = [] # 遍历每一行数据 for idx, row in df.iterrows(): if row[col] <= 150: result.append(row['Patient']) return result # 调用函数 print(get_patients_under_150(df))
输出结果:
['Bob', 'Phil', 'Jessica']
更高效的Pandas矢量化实现(推荐)
Pandas原生不建议用for循环遍历行,矢量化操作速度更快:
def get_patients_under_150(df, col='Weight'): # 筛选体重<=150的行,提取Patient列转为列表 return df[df[col] <= 150]['Patient'].tolist() print(get_patients_under_150(df))
输出同样是:
['Bob', 'Phil', 'Jessica']
内容的提问来源于stack exchange,提问作者lemon
相关产品推荐
相关产品推荐

