Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add pandas data to an existing csv file?

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 loaded data.

like image 908
Ayoub Ennassiri Avatar asked Jul 08 '13 15:07

Ayoub Ennassiri


People also ask

How do I add data to an existing CSV file in Python?

Open your CSV file in append mode Create a file object for this file. Pass the file object and a list of column names to DictWriter() You will get an object of DictWriter. Pass the dictionary as an argument to the writerow() function of DictWriter (it will add a new row to the CSV file).

How do I add data to an existing DataFrame pandas?

append() function is used to append rows of other dataframe to the end of the given dataframe, returning a new dataframe object. Columns not in the original dataframes are added as new columns and the new cells are populated with NaN value.


1 Answers

You can specify a python write mode in the pandas to_csv function. For append it is 'a'.

In your case:

df.to_csv('my_csv.csv', mode='a', header=False) 

The default mode is 'w'.

If the file initially might be missing, you can make sure the header is printed at the first write using this variation:

output_path='my_csv.csv' df.to_csv(output_path, mode='a', header=not os.path.exists(output_path)) 
like image 166
tlingf Avatar answered Sep 27 '22 23:09

tlingf