0

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:

enter image description here

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:

enter image description here

But if I ran the same code with data2, the headers will be displayed again:

enter image description here

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.

Chen
  • 860
  • 10
  • 32
  • Does this answer your question? [How do you remove the column name row when exporting a pandas DataFrame?](https://stackoverflow.com/questions/19781609/how-do-you-remove-the-column-name-row-when-exporting-a-pandas-dataframe) – Shu ba Jan 11 '23 at 14:28
  • 1
    It sounds like you know which headers will be in your CSV, in which case I'd suggest you save the CSV without any headers, then add the headers when you need to read the table in – mitoRibo Jan 11 '23 at 14:28

3 Answers3

3

Only add the headers if the file does not exist:

import pandas
import os

data = pd.DataFrame({'a': [0], 'b': [1]})
data2 = pd.DataFrame({'a': [2], 'b': [3]})
path = './data.csv'

data.to_csv(path, mode='a', header=not os.path.exists(path))
data2.to_csv(path, mode='a', header=not os.path.exists(path))

Result

Plagon
  • 2,689
  • 1
  • 11
  • 23
1

Use header=None after the first export:

data = pd.DataFrame(data, index=[0])
data.to_csv(path, mode='a')

data2 = pd.DataFrame(data2, index=[0])
data2.to_csv(path, mode='a', header=None)

Output:

,a,c,d
0,1,2,3
0,2,3,4
mozway
  • 194,879
  • 13
  • 39
  • 75
-1

To append new data without header just try to set header=False for next rows

Hana Bzh
  • 2,212
  • 3
  • 18
  • 38