I want to write my DataFrame to a CSV file. The result is shown below. The rows are out of alignment with each other. Do you have any suggestion to solve this problem?
Code :
dataframe.to_csv(data,sep="",index=False,header=False,encoding='ascii',
float_format='%10.4f',quoting=csv.QUOTE_NONE, escapechar=" ", mode='a+')
Content of the file.csv :
++++++++++++++++++++++++ C1 c2 c3 c2 1 1.111 1.111 1.111 2 23.261 1.111 1.111 3 138.383 1.111 1.111 2 228.717 1.111 1.111 5 358.225 1.111 1.111 6 268.173 1.111 1.111 7 577.311 1.111 1.111 8 687.623 1.111 1.111 3 737.357 1.111 1.111 11 317.185 1.111 1.111 11 1116.813 1.111 1.111 12 1126.521 1.111 1.111 13 1151.325 1.111 1.111 22 2273.853 1.111 1.111 23 2583.581 1.111 1.111 22 2618.822 1.111 1.111 25 1.111 1.111 23.261 26 23.261 1.111 23.261 27 138.383 1.111 23.261 28 228.717 1.111 23.261 23 358.225 1.111 23.261
csv files aren't supposed to be vertically aligned in that fashion. They are supposed to have values separated by commas. You seem to want nicely formatted ascii.
print dataframe.__repr__()
C1 c2 c3 c2.1
0 1 1.111 1.111 1.111
1 2 23.261 1.111 1.111
2 3 138.383 1.111 1.111
3 2 228.717 1.111 1.111
4 5 358.225 1.111 1.111
5 6 268.173 1.111 1.111
6 7 577.311 1.111 1.111
7 8 687.623 1.111 1.111
8 3 737.357 1.111 1.111
9 11 317.185 1.111 1.111
10 11 1116.813 1.111 1.111
11 12 1126.521 1.111 1.111
12 13 1151.325 1.111 1.111
13 22 2273.853 1.111 1.111
14 23 2583.581 1.111 1.111
15 22 2618.822 1.111 1.111
16 25 1.111 1.111 23.261
17 26 23.261 1.111 23.261
18 27 138.383 1.111 23.261
19 28 228.717 1.111 23.261
20 23 358.225 1.111 23.261
or:
with open('./filename.txt', 'w') as fo:
fo.write(dataframe.__repr__())
This can be done by fixing the number of digits and the width of column headers.
Here is how one can fix number of characters in column headers. (Here it is fixed to 10)
for name in df.columns:
df.rename(columns={name: "{:10}".format(name)}, inplace=True)
Specify the format of numbers while writing csv file.
df.to_csv(<path>, float_format='%0.4e')
The only problem with this approach is, it is not possible to specify different formats for different columns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With