将数据追加到CSV文件中

时间:2019-06-06 17:07:25

标签: python pandas dataframe export-to-csv

我正在将数据从数组添加到带有标头的csv文件中。标题在每次迭代后都会出现,而标题应该只出现在顶部。

x=pd.DataFrame({'1st':U_1, '2nd':U_2, '3rd':U_3, '4th':U_4, 
   '5th':U_5, '6th':U_6, '7th':U_7, '8th':U_8,  'Time 
     Stamp':start})
export_csv = x.to_csv (r'/home/pi/Frames/q8.csv', index = None, 
    mode='a', header=True)

这是csv文件中的输出:

  1st,2nd,3rd,4th,5th,6th,7th,8th,Time Stamp
  ,,,,,,,,1559839922.75
  1st,2nd,3rd,4th,5th,6th,7th,8th,Time Stamp
  ,,,,,,,,1559839922.71
  1st,2nd,3rd,4th,5th,6th,7th,8th,Time Stamp
  ,,,,,,,,1559839922.73
  1st,2nd,3rd,4th,5th,6th,7th,8th,Time Stamp
  ,,,,,,,,1559839922.98

2 个答案:

答案 0 :(得分:0)

在创建csv文件时,第一次使用header=True,从开始添加到现有文件开始,使用header=False

答案 1 :(得分:0)

仅使用标题创建csv文件:

import numpy as np

csvheader = x.columns.values
csvheader = csvheader.reshape(1, csvheader.shape[0])

np.savetxt('/home/pi/Frames/q8.csv', csvheader, delimiter='\t', fmt='%s')

然后将数据附加header=False

for loop:
    x.to_csv (r'/home/pi/Frames/q8.csv', index = None, mode='a', header=False)