使用python中的.csv按特定列数据排序 [英] Sorting by Specific Column data using .csv in python
问题描述
我试图订购一个.csv文件,只有300多个条目,并输出它所有的数字值在方言下的一个特定列中排序。
这里是我写的代码,但它只是输出数据,因为它
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)
整个文件中只有50行包含方言红色标签和所有其他都留为空白。
它在.csv(但不是最后一个)的Z列,所以我假设列的索引是25(0是第一个)。
任何帮助将非常感激。
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.
推荐答案
如何使用 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)
您可能需要将选项调整为 read_csv
和 to_csv
以匹配CSV文件的格式。
You may need to adjust the options to read_csv
and to_csv
to match the format of your CSV file.
这篇关于使用python中的.csv按特定列数据排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!