I have some data in a dict that I would like to save as an csv file with pandas:
data = {
"a": 1,
"c": 2,
"d": 3,
}
Which I am trying to save it in this format:
I am doing this with:
data = pd.DataFrame(data, index=[0])
data.to_csv(path, mode='a', columns=None, header=list(data.keys()))
After data
is saved, I will have more entries (dict) that are in the same format as data
that I need to append to the same csv file. Let's suppose I have:
data2 = {
"a": 2,
"c": 3,
"d": 4,
}
I need to append it as this:
But if I ran the same code with data2
, the headers will be displayed again:
Is there a way to automatically add the header if it is the first entry, and for subsequent entries, no header will be added with the same code. I cannot detect in my code which data is the first entry.