数据分析之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}")
相关推荐
2601_962885723 分钟前
如何用 Python 画 K 线图(蜡烛图)?(mplfinance + 均线 + 成交量)
开发语言·python
linux_cfan7 分钟前
videojs v10 源代码系列解读:30 · `SerialRunner` 与 `ConcurrentRunner`
前端
liangshanbo12158 分钟前
面试题:页面需要发起大量 Ajax / HTTP 请求时,如何优化请求性能?
前端·http·ajax
lyz24685938 分钟前
vue3页面因参数未声明而报错的常犯错误
前端·javascript·vue.js
Y38153266239 分钟前
行业动态周报:用新闻 API 追踪一个赛道的声音变化
python·搜索引擎
摸爬滚打的小李41 分钟前
流程图同步AI生成
前端
Hilaku1 小时前
我重写了整个项目,但没人感谢我!
前端·javascript·程序员
零域码客1 小时前
零基础Python爬虫入门:从HTTP协议到 requests + BeautifulSoup 实战
爬虫·python·http
“AI国潮设计-小江”1 小时前
【SDXL实战】用AI生成“财神爷蛋糕×英歌舞人物”潮汕国潮甜品IP,附Prompt与批量生成思路
开发语言·人工智能·python·aigc
DD云验证1 小时前
DD云验证,免费网络验证系统
服务器·python·易语言·网络验证·卡密验证