如何顺序将df从dict_collection追加到csv或excel而不覆盖以前的数据?

时间:2017-06-14 17:39:14

标签: python pandas dataframe

我试图将BDataFrame_collection中的所有df附加到CSV / excel文件,但循环只保存df的最后一次迭代。另外,你知道这个程序是否会在没有编辑器的情况下执行吗?因为,不需要在编辑器中打开运行...感谢SOF fam ....

import csv
import operator  
import pandas as pd
import numpy as np

df = pd.read_csv('hey2.csv',)#file with info

df.columns = df.columns.str.replace(' ', '_')# replacing all spaces for better op

BDataFrame_collection ={}# storage for data frames 
BList = [1,1,1,1,1,1]# size == num of work centers 

###### storing sorted df
######
BDataFrame_collection[0]= df[df.Main_work ==100]
BDataFrame_collection[1]= df[df.Main_work ==101]
BDataFrame_collection[2]= df[df.Main_work ==102]
BDataFrame_collection[3]= df[df.Main_work ==110]
BDataFrame_collection[4]= df[df.Main_work ==200]
BDataFrame_collection[5]= df[df.Main_work ==240]

###### checking for empty df
######
for i in range(0,6):# size == num of work +1 for list op
    if BDataFrame_collection[i].empty : 
        BList[i] = 0

###### Appending non-empty df
######
#for j in range(0,6):

   if BobList[j] == 1:
    BDataFrame_collection[j].to_csv('Z111_filtered.csv',index= False, 
         columns=[
        'Main_work', 'Orderup', 'Notes', 'List_help',
        'Task_elem', 'Material', 'house_Number', 'Description','Date'])
    enter code here

Lmk你找到了什么,谢谢

1 个答案:

答案 0 :(得分:0)

  

问题:...它会重复下面行中的标题。我该如何解决?

  

pandas 0.20.2文档:   pandas.DataFrame.to_csv

     

DataFrame.to_csv (path_or_buf =无,sep =',',na_rep =“,float_format =无,列=无,标头=真,索引= True ,index_label = None,mode ='w',encoding = None,compression = None,quoting = None,quotechar ='“',line_terminator ='\ n',chunksize = None,tupleize_cols = False,date_format = None,doublequote =是的,escapechar = None,decimal ='。')

header : boolean or list of string, default True
     

写出列名。如果给出了字符串列表,则假定它是列名称的别名

  

问题:...但循环只保存df的最后一次迭代

mode=’a’添加到.to_csv(...