Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Pandas DataFrame to CSV

I want to append pandas data frames to the ends of CSV files. The tricky part is when I append rows, some of the times the columns may be different. I want code like this

a = pd.DataFrame([[1, 2]], columns= ["one", "two"])
with open("learn.csv", "w") as f:
    a.to_csv(f, header=True)

a = pd.DataFrame([[1, 2]], columns= ["one", "three"])
with open("learn.csv", "a") as f:
    a.to_csv(f)

to produce a CSV file that looks like this:

one, two, three
1, 2, None
1, None, 2

Answer*

Cancel