Pandas: random column order when writing DataFrame to csv

I am working on a scan function that is continuously written to output.csv . If this is the first pass, it will write the first row with the header column to an empty file. For the next passes, it will append without a header.

My problem is that the order of the columns is mixed up. I would like them to follow the order I specified in df = pd.DataFrame .

 import pandas as pd input = pd.read_csv(input.csv, delimiter=",") run = 0 def crawl(x): global run run = run + 1 #Assign strings a, b, c df = pd.DataFrame({"A": [a], "B": [b], "C": [c]}) if run == 1: df.to_csv("output.csv") if run != 1: df.to_csv("output.csv", header=None, mode="a") input["X"].apply(crawl, axis=1) 
+4
source share
1 answer

Python dictionaries are essentially unordered .

You can explicitly arrange the columns as follows:

 df = df[['A','B','C']] 
+8
source

All Articles