Search code examples
pythonpandasseries

pandas.Series.to_csv or pandas.Series.to_excel - How to export two serie into on csv or xlsx file?


I have those series :

d = {'a': 1, 'b': 2, 'c': 3}
ser = pd.Series(data=d, index=['a', 'b', 'c']).rename('ser')

d2 = {'adf': 3, 'dfg': 6}
ser2 = pd.Series(data=d2, index=['adf', 'dfg']).rename('ser2')

I can export them individually as csv with :

ser.to_csv('ser.csv',sep=';')
ser2.to_csv('ser2.csv',sep=';')

I would like to export them into one common csv file :

enter image description here

How should I proceed ?

Thanks in advance !


Solution

  • While I advise against including the series name halfway down your csv file, as it will make parsing the csv much more difficult, you can achieve this by using the mode parameter in pandas' to_csv method:

    ser.rename('ser').to_csv('series.csv', sep=';')
    ser2.rename('ser2').to_csv('series.csv', sep=';', mode='a')
    

    This will result in a csv containing:

    ;ser
    a;1
    b;2
    c;3
    ;ser2
    adf;3
    dfg;6