数据分析之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}")
相关推荐
孙启超24 分钟前
【AI应用开发】Agent 无限 loop(反复调用同一个工具)如何规避?
人工智能·python·算法·llm·agent·loop·ai应用开发
银-豆豆29 分钟前
Python爬虫
开发语言·爬虫·python
webkubor35 分钟前
一次前端生产白屏复盘:旧 HTML、Hash 资源和 MIME type text/html
前端·前端工程化
不爱土豆唯爱马铃薯43 分钟前
用MonkeyCode做一个野外数据采集表 | MonkeyCode实操系列EP06
人工智能·数据分析
咩咩啃树皮1 小时前
第63篇【终极整合巨作】从零手写原生中后台管理系统|整合62篇全部前端知识点|从头到尾完整架构+全功能逻辑
前端·架构
香吧香1 小时前
Python 基础语法总结
python
IT小盘1 小时前
10-使用Reranker提升RAG回答准确率
人工智能·python
卷无止境1 小时前
Python 装饰器:给函数穿件"外套",到底难在哪?
后端·python
大地之灯1 小时前
从零做一个自己的 CLI
python·agent
gugucoding1 小时前
34.【Java】I/O流(下):NIO与文件操作
java·python·nio