gpt4 book ai didi

python - 对 csv 文件中的每一列进行排序

转载 作者:行者123 更新时间:2023-11-30 23:23:18 24 4
gpt4 key购买 nike

我有一个包含以下条目的 csv 文件:

    Year,Month,Company A, Company B,Company C, .............Company N
1990, Jan, 10, 15, 20, , ..........,50
1990, Feb, 10, 15, 20, , ..........,50

我正在尝试对 A 公司的 csv 文件数据进行排序,依此类推,直到 N 公司。

我的代码在循环中第一次运行时工作正常,但在第二次运行时失败。

    try:
reader = csv.DictReader(open(self.filename,'r')) #Try and open the file with csv dictreader
except IOError:
print "Error Opening File -- Check if file exists"

ncols = reader.next()
print ncol.keys()
for key in ncols.keys():
if key != 'Month' and key != 'Year':
print key
result = sorted(reader, key=lambda d: float(d[key]))
result = result[-1]
#print "Year " ,
print result['Year'],
#print "Month ",
print result ['Month'],
print key,
print result[key]

输出:

    Company-E
2008 Oct Company-E 997
Company-D

Traceback (most recent call last):
File "<pyshell#105>", line 1, in <module>
read.ParseData()
File "C:/Users/prince/Desktop/CsvRead.py", line 55, in ParseData
result = result[-1]
IndexError: list index out of range

最佳答案

我建议使用 pandas :

import pandas
df = pandas.read_csv(filename)
for col in df.columns:
if col != 'Month' and col != 'Year':
df = df.sort(col)
df.to_csv(out_filename, index=False)

关于python - 对 csv 文件中的每一列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24056523/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com