Sometimes, we want to add Python Pandas data to an existing CSV file.
In this article, we’ll look at how to add Python Pandas data to an existing CSV file.
How to add Python Pandas data to an existing CSV file?
To add Python Pandas data to an existing CSV file, we can use the df.to_csv
method.
For instance, we write:
import pandas as pd
df = pd.read_csv('foo.csv', index_col=0)
with open('foo.csv', 'a') as f:
(df + 5).to_csv(f, header=False)
to read the content of foo.csv with read_csv
.
Then we call open
with 'foo.csv'
to open the file with 'a'
permission, which is append.
And we call to_csv
on df + 5
with file f
to append the new values to foo.csv.
We set header
to False
to skip adding headers.
Therefore, if foo.txt originally has:
,A,B,C
0,1,2,3
1,4,5,6
Then we get:
,A,B,C
0,1,2,3
1,4,5,6
0,6,7,8
1,9,10,11
after calling to_csv
on df + 5
.
Conclusion
To add Python Pandas data to an existing CSV file, we can use the df.to_csv
method.