在.to_csv()方法生成的csv中,是否有任何熊猫方法在每行的末尾添加逗号?

时间:2018-08-22 11:55:38

标签: pandas dataframe python-3.6

我正在使用以下代码从pandas数据帧生成一个csv文件-

full_df.to_csv("../output.csv", quotechar='"', quoting = csv.QUOTE_ALL, index=False, columns=['ProductId','SkuId','EAN','Brand'])

要求是在标头和值中都加上双引号,并且按预期方式工作。 但是由于某些要求,在这里我还需要在每行的最后添加一个逗号。所以我将代码更新如下-

full_df.to_csv("../output.csv", quotechar='"', quoting = csv.QUOTE_ALL, index=False, columns=['ProductId','SkuId','EAN','Brand',''])

但是它也在逗号后面加上双引号,Notepad ++格式的生成的csv的一些片段如下-

"ProductId","SkuId","EAN","Brand",""
"17447","17447-562","7390000000000.0","Champion",""

以下是预期结果-

"ProductId","SkuId","EAN","Brand",
"17447","17447-562","7390000000000.0","Champion",

由于原始csv的记录超过7万条,是否有任何方法可以实现而无需重复csv?

1 个答案:

答案 0 :(得分:3)

通过@yesarka使用解决方案:

full_df = pd.DataFrame({'ProductId':list('abcdef'),
                   'SkuId':[4,5,4,5,5,4],
                   'EAN':[7,8,9,4,2,3],
                   'Brand':[1,3,5,7,1,0],
                   'E':[5,3,6,9,2,4],
                   'F':list('aaabbb')})

print (full_df)
  ProductId  SkuId  EAN  Brand  E  F
0         a      4    7      1  5  a
1         b      5    8      3  3  a
2         c      4    9      5  6  a
3         d      5    4      7  9  b
4         e      5    2      1  2  b
5         f      4    3      0  4  b

a = full_df.to_csv(quotechar='"', 
               quoting = csv.QUOTE_ALL, 
               line_terminator = ',\n',
               index=False, columns=['ProductId','SkuId','EAN','Brand'])
print (a)
"ProductId","SkuId","EAN","Brand",
"a","4","7","1",
"b","5","8","3",
"c","4","9","5",
"d","5","4","7",
"e","5","2","1",
"f","4","3","0",