简体   繁体   中英

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:

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:

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.

Any help is appreciated, thank you.

Instead of dct={} just do this:

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 is part of collections module.

Docs: link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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