如何将dict\ u集合中的df顺序追加到csv或excel中,而不覆盖以前的数据?

2024-10-01 13:33:50 发布

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

我试图将BDataFrame\u集合中的所有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

知道你发现了什么,谢谢


Tags: columnscsvimportdfformainas编辑器
1条回答
网友
1楼 · 发布于 2024-10-01 13:33:50

Question: ...it repeats the headers in rows below. how can i fix that


pandas 0.20.2 documentation: pandas.DataFrame.to_csv

DataFrame.to_csv(path_or_buf=None, sep=’, ’, na_rep=”, float_format=None, columns=None, header=True, index=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=True, escapechar=None, decimal=’.’)

header : boolean or list of string, default True

Write out column names. If a list of string is given it is assumed to be aliases for the column names


Question: ... but the loop only saves the last iteration of the df

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

相关问题 更多 >