How to add pandas data to an existing csv file?

后端 未结 6 1360
离开以前
离开以前 2020-11-22 10:02

I want to know if it is possible to use the pandas to_csv() function to add a dataframe to an existing csv file. The csv file has the same structure as the load

6条回答
  •  悲哀的现实
    2020-11-22 10:27

    A little helper function I use with some header checking safeguards to handle it all:

    def appendDFToCSV_void(df, csvFilePath, sep=","):
        import os
        if not os.path.isfile(csvFilePath):
            df.to_csv(csvFilePath, mode='a', index=False, sep=sep)
        elif len(df.columns) != len(pd.read_csv(csvFilePath, nrows=1, sep=sep).columns):
            raise Exception("Columns do not match!! Dataframe has " + str(len(df.columns)) + " columns. CSV file has " + str(len(pd.read_csv(csvFilePath, nrows=1, sep=sep).columns)) + " columns.")
        elif not (df.columns == pd.read_csv(csvFilePath, nrows=1, sep=sep).columns).all():
            raise Exception("Columns and column order of dataframe and csv file do not match!!")
        else:
            df.to_csv(csvFilePath, mode='a', index=False, sep=sep, header=False)
    

提交回复
热议问题