数据分析之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}")
相关推荐
前端繁华如梦3 分钟前
# 从 73000 行压缩代码到 TypeScript 模块化:我把一个 Three.js FPS 游戏 1:1 复刻了一遍
前端
Penge6667 分钟前
React Context 详解:从 Props 传递到跨组件状态共享
前端
Penge66616 分钟前
React 事件处理:bind(this) 原理与实际开发常用写法
前端
aifannihao18 分钟前
GitHub Actions 锁文件实测:6 个 uses 只锁住 2 个
python·ci/cd·标准库·供应链安全·github actions
ZhengEnCi27 分钟前
小白用 AI 做官网完全指南:不用框架的六格清单,双击就能打开
前端·html·ai编程
2601_9679801132 分钟前
使用gensim处理文本(1)语料库与词向量空间
python·自然语言处理·gensim·词向量·文本分析
zhanlang021742 分钟前
HTML 零基础入门到企业实战【第五章 5.2】图片路径精讲:绝对路径、相对路径、网络路径(新手必踩坑点)
前端·html
夕水1 小时前
我用trae重构了ew-color-picker,一个插件化架构的现代颜色选择器
前端·javascript·开源
Penge6661 小时前
React JSX 核心语法:从入门到业务开发实战
前端
zhanlang02171 小时前
HTML 零基础入门到企业实战全套教程【第五章 5.5 综合案例:图文影音展示页面开发】
前端·html