简体   繁体   English

熊猫:用Windows行结尾写CSV文件

[英]Pandas: Write CSV file with Windows line ending

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 (ie, \\r\\n instead of \\r\\r\\n ). 我怎样才能实现这一点(即\\r\\n而不是\\r\\r\\n )。 My operating system is Windows 10. 我的操作系统是Windows 10。

The following is from a submission to Kaggle. 以下是提交给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. 我不得不自己编写输出循环,因为大熊猫坚持同时添加CR和LF,这给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. 需要注意的主要事项是使用io.open,在open调用中设置newline ='\\ n',并在每次写调用结束时添加'\\ n'。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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