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

Time:04-28

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 !

CodePudding user response:

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

CodePudding user response:

You could use the shell command cat ser2.csv >> ser.csv, or in Python:

with open('ser_combined.csv', 'w') as f:
    for fname in ['ser.csv', 'ser2.csv']:
        with open(fname) as in_f:
            f.write(in_f.read())
  • Related