python原地去重实战案例笔记

数据样例:👇

最终想要的结果:

一、解决办法

思路:处理逐个元素检查是否已经出现过,重复的元素用空字符串替换。

python 复制代码
# 原始数据
data = [
    ['数据1', '数据2', '数据3', '数据4', '数据5'],
    ['D', 'A', 'S', 'Q', 'J'],
    ['Y', 'L', 'D', 'J', 'O'],
    ['G', 'X', 'X', 'P', 'V'],
    ['L', 'H', 'Z', 'M', 'D'],
    ['N', 'X', 'J', 'B', 'Z']
]

# 创建一个集合来存储已经出现过的值
seen = set()

# 处理数据
result = [data[0]]  # 保留表头
for row in data[1:]:
    new_row = []
    for item in row:
        if item not in seen:
            new_row.append(item)
            seen.add(item)
        else:
            new_row.append('')
    result.append(new_row)

# 打印结果
for row in result:
    print('\t'.join(row))

但在现实生活中我们可能都是直接读取excel,来获取数据,它的写法为:

python 复制代码
import pandas as pd

# 读取 Excel 文件中的数据
file_path = '公式练习题原地去重.xlsx'  # 设置要读取的 Excel 文件路径
df = pd.read_excel(file_path)

# 将数据转换为列表形式
data = df.values.tolist()

# 创建一个集合来存储已经出现过的值
seen = set()

# 处理数据
result = [df.columns.tolist()]  # 保留表头,将列名转换为列表并放入结果列表中
for row in data:
    new_row = []
    for item in row:
        if item not in seen:
            # 如果当前元素不在已出现的集合中,将其添加到新行列表,并将其加入集合
            new_row.append(item)
            seen.add(item)
        else:
            # 如果当前元素已出现过,在新行列表中添加空字符串
            new_row.append('')
    result.append(new_row)

# 将结果转换回 DataFrame 并保存为新的 Excel 文件
result_df = pd.DataFrame(result[1:], columns=result[0])
result_df.to_excel('processed_output.xlsx', index=False)
# 打印结果(可选)
for row in result:
    print('\t'.join([str(i) for i in row]))
相关推荐
金銀銅鐵1 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf2 小时前
Agent 流程编排
后端·python·agent
copyer_xyf2 小时前
Agent RAG
后端·python·agent
copyer_xyf2 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf3 小时前
Agent 记忆管理
后端·python·agent
星云穿梭18 小时前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵18 小时前
用 Pygame 实现 15 puzzle
python·数学·游戏
黄忠1 天前
大模型之LangGraph技术体系
python·llm
hboot2 天前
AI工程师第二课 - 数据处理
人工智能·python·数据分析
用户8356290780512 天前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python