Skip to content
Advertisement

Remove leading comma in header when using pandas to_csv

By default to_csv writes a CSV like

,a,b,c
0,0.0,0.0,0.0
1,0.0,0.0,0.0
2,0.0,0.0,0.0

But I want it to write like this:

a,b,c
0,0.0,0.0,0.0
1,0.0,0.0,0.0
2,0.0,0.0,0.0

How do I achieve this? I can’t set index=False because I want to preserve the index. I just want to remove the leading comma.

df = pd.DataFrame(np.zeros((3,3)), columns = ['a','b','c'])
df.to_csv("test.csv") # this results in the first example above.

Advertisement

Answer

It is possible by write only columns without index first and then data without header in append mode:

df = pd.DataFrame(np.zeros((3,3)), columns = ['a','b','c'], index=list('XYZ'))

pd.DataFrame(columns=df.columns).to_csv("test.csv", index=False)
#alternative for empty df
#df.iloc[:0].to_csv("test.csv", index=False)
df.to_csv("test.csv", header=None, mode='a')

df = pd.read_csv("test.csv")
print (df)
     a    b    c
X  0.0  0.0  0.0
Y  0.0  0.0  0.0
Z  0.0  0.0  0.0
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement