简体   繁体   English

python保留输出csv文件的列顺序

[英]python preserving output csv file column order

The issue is common, when I import a csv file and process it and finally output it, the order of column in the output csv file may be different from the original one,for instance: 这个问题很常见,当我导入一个csv文件并对其进行处理并最终将其输出时,输出csv文件中的列顺序可能与原始文件不同,例如:

dct={}
dct['a']=[1,2,3,4]
dct['b']=[5,6,7,8]
dct['c']=[9,10,11,12]

header = dct.keys()
rows=pd.DataFrame(dct).to_dict('records')

with open('outTest.csv', 'wb') as f:
    f.write(','.join(header))
    f.write('\n')
    for data in rows:
        f.write(",".join(str(data[h]) for h in header))
        f.write('\n')

the original csv file is like: 原始的csv文件如下所示:

a,c,b
1,9,5
2,10,6
3,11,7
4,12,8

while I'd like to fixed the order of the column like the output: 而我想固定输出的列顺序:

a,b,c
1,5,9
2,6,10
3,7,11
4,8,12

and the answers I found are mostly related to pandas , I wonder if we can solve this in another way. 我发现的答案大多与pandas有关,我想知道我们是否可以通过其他方式解决这个问题。

Any help is appreciated, thank you. 任何帮助表示赞赏,谢谢。

Instead of dct={} just do this: 代替dct={}做到这一点:

from collections import OrderedDict
dct = OrderedDict()

The keys will be ordered in the same order you define them. 键将按照您定义键的顺序排列。

Comparative test: 对比测试:

from collections import OrderedDict
dct = OrderedDict()
dct['a']=[1,2,3,4]
dct['b']=[5,6,7,8]
dct['c']=[9,10,11,12]

stddct = dict(dct)  # create a standard dictionary

print(stddct.keys())  # "wrong" order
print(dct.keys())     # deterministic order

result: 结果:

['a', 'c', 'b']
['a', 'b', 'c']

Try using OrderedDict instead of dictionary . 尝试使用OrderedDict而不是dictionary OrderedDict is part of collections module. OrderedDictcollections模块的一部分。

Docs: link 文件: 连结

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM