python写csv文件数字排序自然数,使用python中的.csv按特定列数据排序

I'm trying to order a .csv file with just over 300 entries and output it all back out ordered by the numerical values in one specific column under a dialect.

Here's the code I've written so far but it just seems to output the data as it went in

import csv

import itertools

from itertools import groupby as gb

reader = csv.DictReader(open('Full_List.csv', 'r'))

groups = gb(reader, lambda d: d['red label'])

result = [max(g, key=lambda d: d['red label']) for k, g in groups]

writer = csv.DictWriter(open('output.csv', 'w'), reader.fieldnames)

writer.writeheader()

writer.writerows(result)

There's only 50 rows in the whole file that contain a value under the dialect "red label" and all the others are left blank.

It's in the Z column on the .csv(but not that last one) so I'd assume the index of the column is 25(0 being the first).

Any help would be greatly appreciated.

解决方案

How about using pandas?

import pandas as pd

df = pd.read_csv('Full_List.csv')

df = df.sort('red label')

df.to_csv('Full_List_sorted.csv', index=False)

You may need to adjust the options to read_csv and to_csv to match the format of your CSV file.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值