Example:
import pandas as pd
df = pd.DataFrame({'A':[1,2], 'B':[3,4]})
df.to_csv('test.csv', line_terminator='\r\n')
gives the file
,A,B\r
\r\n
0,1,3\r
\r\n
1,2,4\r
\r\n
however, I would like to have
,A,B\r\n
0,1,3\r\n
1,2,4\r\n
How can I achieve this (i.e., \r\n
instead of \r\r\n
). My operating system is Windows 10.
When you write pandas DataFrame to an existing CSV file, it overwrites the file with the new contents. To append a DataFrame to an existing CSV file, you need to specify the append write mode using mode='a' .
To write a pandas DataFrame to a CSV file, you will need DataFrame. to_csv . This function offers many arguments with reasonable defaults that you will more often than not need to override to suit your specific use case.
If you pass it an open file it will keep it open (reading from the current position), if you pass a string then read_csv will open and close the file.
Pandas is better then csv for managing data and doing operations on the data. CSV doesn't provide you with the scientific data manipulation tools that Pandas does.
The following is from a submission to Kaggle. Hope you'll find it useful. I had to write the output loop myself as pandas insisted on adding both CR and LF and it caused problems for Kaagle.
import io
with io.open('../output/submission_{}.csv'.format('22-Sep-2018-Try-Something_with_re'), 'w', newline='\n') as of:
of.write('fullVisitorId,PredictedLogRevenue\n')
for ind in out_log.index:
of.write('{},{}\n'.format(ind, out_log['PredictedLogRevenue'][ind]))
The main things to notice is the use of io.open, setting newline='\n' in the open call, and adding '\n' at the end of each write call.
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