Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Series to Excel

Tags:

python

pandas

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')
like image 604
ojdo Avatar asked Apr 29 '14 13:04

ojdo


People also ask

How do I convert a panda to Excel?

Use pandas to_excel() function to write a DataFrame to an excel sheet with extension . xlsx. By default it writes a single DataFrame to an excel file, you can also write multiple sheets by using an ExcelWriter object with a target file name, and sheet name to write to.

How do I convert a Pandas series to a list?

How to use the tolist() method to convert pandas series to list. To convert a pandas Series to a list, simply call the tolist() method on the series which you wish to convert.


2 Answers

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')
like image 76
Phillip Cloud Avatar answered Sep 30 '22 06:09

Phillip Cloud


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 /
like image 28
ojdo Avatar answered Sep 30 '22 05:09

ojdo