Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 324
JacksonCounty Avatar asked Mar 03 '23 21:03

JacksonCounty


2 Answers

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
like image 64
jezrael Avatar answered Mar 05 '23 16:03

jezrael


Alternatively, try reseting the index so it becomes a column in data frame, named index. This works with multiple indexes as well.

df = df.reset_index()
df.to_csv('output.csv', index = False)
like image 29
Parfait Avatar answered Mar 05 '23 16:03

Parfait