数据分析之Python对数据分组排序

原数据样例:

|----|-------------------|----|
| 名字 | 技能 | 性别 |
| 张三 | 打篮球、打羽毛球、打乒乓球、打游戏 | 男 |

最后的结果:

|----|------|----|----|
| 名字 | 技能 | 性别 | 排序 |
| 张三 | 打篮球 | 男 | 1 |
| 张三 | 打羽毛球 | 男 | 2 |
| 张三 | 打乒乓球 | 男 | 3 |
| 张三 | 打游戏 | 男 | 4 |

1、读取csv文件数据

复制代码
input_csv_file = 'data.csv'
output_csv_file = 'sorted_data_with_qualifications.csv'

# 读取CSV文件并处理数据
with open(input_csv_file, newline='', encoding='utf-8') as csvfile:
    reader = csv.reader(csvfile)
    header = next(reader)  # 跳过表头

2、对数据中的某一个字段进行分组排序

原数据中第二列中是按照、分隔的。

复制代码
sorted_data = []
    for row in reader:
        person = row[0]
        qualifications = row[1].split('、')  # 按顿号分割资质能力

        sorted_qualifications = sorted(qualifications)  # 对资质能力进行排序

        for idx, qualification in enumerate(sorted_qualifications,start=1):

            sorted_data.append([person, qualification, idx, row[2]])  # 添加序号和组别

3、结果保存到csv文件中

复制代码
# 将处理后的数据写入新的CSV文件
with open(output_csv_file, 'w', newline='', encoding='utf-8') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['','',''])  # 写入新表头
    for row in sorted_data:
        writer.writerow(row)  # 写入每行数据

完整代码

复制代码
import csv

# 假设CSV文件名为"data.csv",我们将结果保存到"sorted_data_with_qualifications.csv"
input_csv_file = 'data.csv'
output_csv_file = 'sorted_data_with_qualifications.csv'

# 读取CSV文件并处理数据
with open(input_csv_file, newline='', encoding='utf-8') as csvfile:
    reader = csv.reader(csvfile)
    header = next(reader)  # 跳过表头

    sorted_data = []
    for row in reader:
        person = row[0]
        qualifications = row[1].split('、')  # 按顿号分割资质能力

        sorted_qualifications = sorted(qualifications)  # 对资质能力进行排序

        for idx, qualification in enumerate(sorted_qualifications,start=1):

            sorted_data.append([person,row[1], qualification, idx, row[2]])  # 添加序号和组别

# 将处理后的数据写入新的CSV文件
with open(output_csv_file, 'w', newline='', encoding='utf-8') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['','',''])  # 写入新表头
    for row in sorted_data:
        writer.writerow(row)  # 写入每行数据

print(f"Sorted data with qualifications has been written to {output_csv_file}")
相关推荐
m沐沐1 分钟前
【机器学习】矿物识别系统实战——六种填充方法×六种模型全面对比
人工智能·python·深度学习·机器学习·矿物识别
软糖姐姐10 分钟前
Python:__closure__ 详解
python·闭包·__closure__·自由变量·cell对象
月光船幽幽15 分钟前
四层公理框架驱动AI健康诊断
人工智能·python·科技·算法·安全
郝学胜-神的一滴39 分钟前
力扣 692:巧用小顶堆高效求解前K个高频单词
java·数据结构·python·程序人生·算法·leetcode·职场和发展
栈溢出的浪漫39 分钟前
Python单元测试框架覆盖率-Coverage
python·单元测试·工具·覆盖率·coverage
问商十三载40 分钟前
RAG的适用边界在哪里?2026年价值与局限详解
大数据·前端·人工智能
淼澄研学41 分钟前
Python构建AI应用:从环境配置到FastAPI部署的5个实操步骤
人工智能·python·fastapi
1570925113444 分钟前
优先队列:从Java源码到实战
开发语言·python
Python私教1 小时前
Django + AI 做智能工单系统:自动分类、重复合并、服务时限与人工审批实战
人工智能·python·django
qq_22589174661 小时前
2026 计算机专业毕业设计选题推荐|Python 数据分析 / 可视化 / 推荐 / 预测(持续更新)
python·数据分析·课程设计