Pandas:以Windows行结尾写入CSV文件

2024-06-26 02:51:24 发布

您现在位置:Python中文网/ 问答频道 /正文

示例:

import pandas as pd
df = pd.DataFrame({'A':[1,2], 'B':[3,4]})
df.to_csv('test.csv', line_terminator='\r\n')

提供文件

^{pr2}$

但是,我想

,A,B\r\n
0,1,3\r\n
1,2,4\r\n

如何实现这一点(即,\r\n而不是{})。我的操作系统是Windows10。在


Tags: 文件csvtotestimport示例dataframepandas
1条回答
网友
1楼 · 发布于 2024-06-26 02:51:24

以下是提交给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调用中设置newline='\n',并在每个write调用的末尾添加'\n'。在

相关问题 更多 >