Pandas中对percent≥40%的行做条件判断并拼接指定格式结果
Pandas 筛选+文本拼接实现方案
核心调整点
- 不再直接覆盖原DataFrame,将筛选结果单独存在临时变量中,支撑分支判断逻辑
- 增加空结果分支:筛选后无匹配记录时直接返回明确提示,避免后续拼接逻辑报错
- 采用pandas向量化字符串操作完成格式拼接,比普通Python循环执行效率更高,适配大体积数据集
完整可运行代码
# 按条件筛选,不修改原始df数据 matched_records = df[df["percent"] >= 40].copy() # 分支逻辑控制 if matched_records.empty: final_output = "当前无percent值≥40%的匹配门店记录" else: # 逐行按指定规则生成文本 matched_records["text_line"] = ( "from store " + matched_records["store_id"].astype(str) + " - " + matched_records["store_name"].astype(str) + ", " + matched_records["items"].astype(str) + " items were selected out of " + matched_records["max"].astype(str) + " possible, with " + matched_records["percent"].astype(str) + "% achieved" ) # 多行文本拼接为最终输出 final_output = "\n".join(matched_records["text_line"].tolist())
效果验证
使用给定的示例数据集运行代码,最终输出的final_output完全匹配要求格式:
from store 2 - yellow, 4 items were selected out of 10 possible, with 40.0% achieved
from store 3 - white, 4 items were selected out of 2 possible, with 350.0% achieved
常见问题提示
如果拼接后出现小数格式不统一(比如percent字段显示为40而非要求的40.0),可以在拼接文本前增加一行数值格式化代码:matched_records["percent"] = matched_records["percent"].round(1).astype(str)
内容的提问来源于stack exchange,提问作者ApacheOne
相关产品推荐
相关产品推荐

