8

The pandas.Series object does have many to_* functions, yet it lacks a to_excel function. Is there an easier/better way to accomplish the export in line 3 of this snippet? It feels clunky to first convert the Series to a DataFrame simply for a simple I/O:

import numpy as np
import pandas as pd
s = pd.Series([1,3,5,np.nan,6,8])
pd.DataFrame(s).to_excel('s.xlsx', 's')
scls
  • 16,591
  • 10
  • 44
  • 55
ojdo
  • 8,280
  • 5
  • 37
  • 60

2 Answers2

15

You can either:

1. construct a DataFrame from the start,

in which case you've already answered your own question.

2. Use Series.to_frame()

s.to_frame(name='column_name').to_excel('xlfile.xlsx', sheet_name='s')
Community
  • 1
  • 1
Phillip Cloud
  • 24,919
  • 11
  • 68
  • 88
  • 1
    Ok, so the answer is actually "nope". But the `to_frame` queues nice, saves me one line for a manual s.name change and looks less like an ugly typecast (which the pd.DataFrame looks like to me) in my context. – ojdo Apr 29 '14 at 13:39
  • This might be a good first pull request over on github if you're interested, though I'm not sure how common writing a single column to an Excel table is. – Phillip Cloud Apr 29 '14 at 13:40
  • If it happens to me a second time I will consider doing that; it just happened to me from summing over a DataFrame. – ojdo Apr 29 '14 at 13:43
  • FYI, there's also a `DataFrame.squeeze()` method that will turn a single column `DataFrame` into a `Series`. – Phillip Cloud Apr 29 '14 at 13:45
  • Did anyone created that issue on github? I couldn't find it. – Ivan May 14 '15 at 18:51
  • I opened an issue about this several times ago https://github.com/pandas-dev/pandas/issues/8825 – scls Dec 01 '16 at 06:02
3

New in 0.20: Series.to_excel()

Beginning with pandas version 0.20, Series now supports to_excel directly (see PR #8825 for details):

import pandas as pd
s = pd.Series([0, 1, 2, 4, 8, 16], name='a_series')
s.to_excel('foo.xlsx')

Contents of file foo.xlsx:

  |  A | B         | 
--+----+-----------+---------------------
1 |    | a_series  | 
2 |  0 | 0         | 
3 |  1 | 1         | 
4 |  2 | 2         | 
5 |  3 | 4         | 
6 |  4 | 8         | 
7 |  5 | 16        | 
-.           ,---------------------------
  \ Sheet 1 /  \ Sheet 2 / \ Sheet 3 /
ojdo
  • 8,280
  • 5
  • 37
  • 60
  • 1
    Is there a way to change the writing of Series from vertical to horizontal, so that the index is used as columns? – Krzysztof Słowiński Jan 09 '18 at 12:42
  • 1
    @KrzysztofSłowiński not directly, only through `s.to_frame().T.to_excel(...)`, using DataFrame's transpose operation. – ojdo Mar 04 '21 at 17:43