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]))
相关推荐
hboot12 小时前
AI工程师第二课 - 数据处理
人工智能·python·数据分析
用户83562907805116 小时前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
用户83562907805118 小时前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
黄忠1 天前
01-系统架构设计-LangGraph状态机与多源异构RAG
python
zzzzzz3101 天前
假如我是掘金管理员,我先给评论区装个'代码审查'系统
python·程序员·机器人
砍材农夫1 天前
python环境|conda安装和使用(2)
后端·python
程序员龙叔2 天前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试
用户8356290780512 天前
使用 Python 操作 Word 内容控件
后端·python
码云骑士2 天前
32-慢查询排查全流程(下)-索引优化实战与最左前缀原则
python