如何基于Pandas DataFrame另一列统计符合条件的True值并实现区域推荐
报错原因
在if条件中直接对整个Pandas Series做布尔判断,Python无法直接判定一整组布尔值的真假,因此抛出该错误。现有代码其余核心问题如下:
- Pandas多条件布尔筛选需要用
&替代Python原生的and,且每个判断条件需要用括号包裹,否则会触发运算优先级错误 - 手动遍历Series的开发方式效率极低,也不符合Pandas向量化计算的设计逻辑,分组计数需求可以直接用Pandas自带API实现
- 原代码返回值为数值类型,不符合需求要求的字符串返回格式
修复后的完整实现代码
import pandas as pd def district_recommender(df, min_budget = 17.0, max_budget = 30.0): # 筛选价格在预算区间内的记录 budget_mask = (df['price'] >= min_budget) & (df['price'] <= max_budget) filtered_df = df[budget_mask] # 按区域分组统计符合条件的数量,默认按数量降序排列 district_count = filtered_df['district'].value_counts() # 取数量最多的区域和对应计数 top_district = district_count.idxmax() top_count = district_count.max() # 按要求格式返回字符串 return f"For your specified budget {min_budget} - {max_budget}, the {top_district} District has {top_count} opportunities within your criteria"
运行测试
使用示例DataFrame调用函数:
df = pd.DataFrame({'district':['A','B','C','D','B','B','A'], 'price': [10.0,20.0,50.0,27.0,21.0,19.0,12.0]}) print(district_recommender(df))
输出结果和要求完全一致:
For your specified budget 17.0 - 30.0, the B District has 3 opportunities within your criteria
内容的提问来源于stack exchange,提问作者burtonian
相关产品推荐
相关产品推荐

