Home >Backend Development >Python Tutorial >How to Append Pandas DataFrames to Existing CSV Files?
Adding Pandas Data to an Existing CSV File
When dealing with data exploration and manipulation, the pandas library is a powerful tool. One common task is appending data from a pandas DataFrame to an existing CSV file.
To accomplish this, the to_csv() function in pandas provides a flexible solution. By specifying the appropriate write mode, you can add data to an existing CSV file without overwriting its contents.
Solution:
The key to appending data is to use the mode parameter in the to_csv() function. By setting mode='a', you instruct pandas to append the data to the CSV file instead of overwriting it. Here's an example:
df.to_csv('my_csv.csv', mode='a', header=False)
In this example, the df DataFrame is appended to the CSV file named my_csv.csv. The header=False argument ensures that the CSV file's header is not duplicated when appending the data.
Default Mode and Handling Missing Files:
By default, the to_csv() function uses the 'w' mode, which overwrites the existing CSV file. To handle cases where the CSV file may not initially exist, you can use the following variation:
output_path = 'my_csv.csv' df.to_csv(output_path, mode='a', header=not os.path.exists(output_path))
This code checks if the output_path file exists before writing. If it doesn't exist, it prints the header in the first write. Otherwise, it appends the data without the header.
The above is the detailed content of How to Append Pandas DataFrames to Existing CSV Files?. For more information, please follow other related articles on the PHP Chinese website!