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]))
相关推荐
timeDifference₇2 小时前
Python Vibe Coding实操实验报告
开发语言·jvm·python
geovindu3 小时前
python:DecisionTree
开发语言·后端·python·算法
怒放的生命19914 小时前
代码知识库 RAG 问答系统 —— 从 0 到 1 实现教程
python·状态模式·fastapi·全栈开发·ai agent应用开发
geovindu5 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
fengkai45456 小时前
Python运维
运维·python·监控·psutil·ipy
Fancy.7616 小时前
:Python条件与循环语句学习总结
python
Wellijohn7 小时前
Python 容器选型实测:list.insert(0) 慢 925 倍,in 慢 6000 倍
python
新*7 小时前
标题全变成一级?靠编号规律找回章节边界
python·正则表达式·pdf解析·文本处理
高洁0110 小时前
多源数据融合:把零散信号拼成一致图景
人工智能·python·机器学习·transformer·迁移学习
郝学胜-神的一滴10 小时前
Effective Python 条款41:试Mix‑In组合式开发
开发语言·pytorch·python·pycharm·numpy