例子:
import pandas as pd
df = pd.DataFrame({'A':[1,2], 'B':[3,4]})
df.to_csv('test.csv', line_terminator='\r\n')
给出文件
,A,B\r
\r\n
0,1,3\r
\r\n
1,2,4\r
\r\n
但是,我想拥有
,A,B\r\n
0,1,3\r\n
1,2,4\r\n
我怎样才能做到这一点(即 \r\n
而不是 \r\r\n
)。我的操作系统是 Windows 10。
最佳答案
以下内容来自提交给 Kaggle 的文章。希望你会发现它有用。我不得不自己编写输出循环,因为 pandas 坚持要同时添加 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]))
主要需要注意的是io.open的使用,在open调用中设置newline='\n',在每次write调用的末尾添加'\n'。
关于python - Pandas:编写带有 Windows 行结尾的 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41433269/