我如何按照excel排序的方式对csv文件中的列进行排序。下面是我目前为止的csv文件和代码段。我想对ArrivalTime进行排序,因此特定的Process和ServiceTime会继续运行。感谢您提供任何帮助或建议。
CSV:
Process,ArrivalTime,ServiceTime
A,0,3
B,2,6
C,4,4
D,6,5
E,8,2
和我的代码:
import csv
from collections import defaultdict
columns = defaultdict(list)
with open('file.csv') as f:
reader = csv.DictReader(f)
for row in reader:
for (k,v) in row.items():
columns[k].append(v)
st = columns['ServiceTime']
at = columns['ArrivalTime']
pr = columns['Process']
答案 0 :(得分:2)
您是否考虑过使用pandas
?它有内置的方法来处理这种情况。
import pandas as pd
# create a dataframe from the file, like an Excel spreadsheet
df = pd.read_csv('file.csv')
df.sort_values('ArrivalTime')
# returns:
Process ArrivalTime ServiceTime
0 A 0 3
1 B 2 6
2 C 4 4
3 D 6 5
4 E 8 2
答案 1 :(得分:0)
我同意你应该使用熊猫......
除此之外,你不需要这里的默认用语。
阅读文件并排序:
import csv
import operator as op
list_of_dicts = []
with open('in.csv','r') as f:
reader = csv.DictReader(f)
for line in reader:
list_of_dicts.append(line)
list_of_dicts.sort(key=op.itemgetter('ArrivalTime'))
把它写回来:
with open('out.csv','w') as f:
writer = csv.DictWriter(f,fieldnames=list_of_dicts[0].keys())
for i in list_of_dicts:
writer.writerow(i)