遍历Pandas DataFrame时跳过特定值,生成有效定制消息
问题:遍历Pandas DataFrame时跳过值为“-”的项生成有效消息
问题场景
我有如下格式的数据:
期望生成的消息格式:
Hello {first_name} {last_name}, this is the list of fruit that you want
- {fruit_0} with {colour_0} colour
- {fruit_1} with {colour_1} colour
- {fruit_2} with {colour_2} colour
预期输出(第一行数据)
Hello Maria White, this is the list of fruit that you want 1. apple with pink colour
实际输出
Hello Maria White, this is the list of fruit that you want 1. apple with pink colour 2. - with - colour 3. - with - colour
原代码
import pandas as pd df = pd.read_excel("fruit.xlsx") for x in df.itertuples(): first_name = x.first_name last_name = x.last_name fruit_0 = x.fruit_0 fruit_1 = x.fruit_1 fruit_2 = x.fruit_2 colour_0 = x.colour_0 colour_1 = x.colour_1 colour_2 = x.colour_2 message = f""" Hello {first_name} {last_name}, this is the list of fruit that you want 1. {fruit_0} with {colour_0} colour 2. {fruit_1} with {colour_1} colour 3. {fruit_2} with {colour_2} colour """ print(message)
解决方案
修改思路
将水果与颜色配对后过滤掉含“-”的无效项,再动态生成列表内容,避免硬编码导致的无效行输出。
修改后的代码
import pandas as pd df = pd.read_excel("fruit.xlsx") for row in df.itertuples(): # 获取用户全名 full_name = f"{row.first_name} {row.last_name}" # 配对所有水果和颜色组合 fruit_colour_pairs = [ (row.fruit_0, row.colour_0), (row.fruit_1, row.colour_1), (row.fruit_2, row.colour_2) ] # 过滤掉值为“-”的无效项 valid_items = [pair for pair in fruit_colour_pairs if pair[0] != "-" and pair[1] != "-"] # 构建消息内容 message_lines = [f"Hello {full_name}, this is the list of fruit that you want"] # 动态生成带有序号的有效列表项 for idx, (fruit, colour) in enumerate(valid_items, start=1): message_lines.append(f"{idx}. {fruit} with {colour} colour") # 拼接并打印消息 message = "\n".join(message_lines) print(message) print("-" * 30) # 分隔不同行数据的输出,可选
代码说明
- 配对过滤:将每组水果和颜色绑定为元组,通过列表推导式筛选掉含“-”的无效组合,确保仅保留有效数据。
- 动态生成列表:使用
enumerate从1开始计数,自动生成带有序号的列表项,避免硬编码固定行数导致的无效内容。 - 格式整洁:先构建消息行的列表,再用换行符拼接成完整字符串,保证输出格式规范。
内容的提问来源于stack exchange,提问作者karinayoo
相关产品推荐
相关产品推荐

