数据分析之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}")
相关推荐
Jazz_z3 分钟前
如何用Python将彩色PDF一键转为黑白(灰度)
java·python·pdf
南雨北斗4 分钟前
vue3 RouterLink链接颜色修改的方法
前端
Richard.Wong5 分钟前
Windows IIS 服务器部署 Vue3 前端项目详细流程
服务器·前端·windows
数据知道5 分钟前
XSS 攻防全解:反射型、存储型、DOM 型实战演示
前端·安全·web安全·网络安全·xss
Nemo_XP6 分钟前
C# gridlookupedit选中内容重复还原操作
服务器·前端·c#
SEO_juper9 分钟前
2026年Schema自动注入实战:用Python批量给1000个页面加上JSON-LD,AI引用率实测提升38%
人工智能·python·json·seo·独立站
大家的林语冰13 分钟前
🎉 Vercel 官宣 Next 16.3 正式发布,GitHub 第一全栈框架再次进化!
前端·javascript·前端框架
zzzll111136 分钟前
HashMap、HashTable、ConcurrentHashMap 详细区别与深度解析
开发语言·python
程序员AI工坊40 分钟前
Agent 开发:ReAct 循环与工具调用实战——从单次调用到自主 Agent
人工智能·后端·python·langchain·agent·react
️学习的小王1 小时前
基于UDP实现简易聊天室(基础版)——Python实现
网络·python·udp