1) Sort the headers(columns) while creating a CSV file
2) Add a new header(column) in a CSV file
For the 1st problem, I have some CSV files, each of them has a column, then I merge these CSV files together. In the final CSV file, the headers are not in the right order.
The correct order should be a, b, c...
but the final CSV file has the header c, b, a
. How can I sort the headers?
# create final csv file iteration
for i in range(lenList - 1):
newcsv = pd.read_csv(csv_list[i + 1])
csv_out = newcsv.merge(oldcsv, on=['Time'], how="outer", sort=True)
oldcsv = csv_out
# saves the final csv file
output_file = "../build/*.csv"
oldcsv.to_csv(output_file, index=False)
For the 2nd problem, When I create CSV files, some 18 columns, and somehave 17 columns. But they should both have 18 columns.
E.g, file1 has columns a, b, c, d
.file2 has columns a,b,c
.
I need them to have same number of colums. So I need to add an empty column to file2.