Skip to content

Commit 0ab4876

Browse files
committed
ENH: Pandas Series provide to_excel method
Closes pandas-dev#8825
1 parent 68d7609 commit 0ab4876

File tree

6 files changed

+84
-58
lines changed

6 files changed

+84
-58
lines changed

doc/source/api.rst

+1
Original file line numberDiff line numberDiff line change
@@ -692,6 +692,7 @@ Serialization / IO / Conversion
692692
Series.to_pickle
693693
Series.to_csv
694694
Series.to_dict
695+
Series.to_excel
695696
Series.to_frame
696697
Series.to_xarray
697698
Series.to_hdf

doc/source/whatsnew/v0.20.0.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,8 @@ Other enhancements
4949
^^^^^^^^^^^^^^^^^^
5050

5151
- ``pd.read_excel`` now preserves sheet order when using ``sheetname=None`` (:issue:`9930`)
52-
5352
- ``pd.cut`` and ``pd.qcut`` now support datetime64 and timedelta64 dtypes (issue:`14714`)
53+
- ``Series`` provides a ``to_excel`` method to output Excel files (:issue:`8825`)
5454

5555
.. _whatsnew_0200.api_breaking:
5656

pandas/core/frame.py

+3-56
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,8 @@
105105
axes_single_arg="{0 or 'index', 1 or 'columns'}",
106106
optional_by="""
107107
by : str or list of str
108-
Name or list of names which refer to the axis items.""")
108+
Name or list of names which refer to the axis items.""",
109+
versionadded_to_excel='')
109110

110111
_numeric_only_doc = """numeric_only : boolean, default None
111112
Include only float, int, boolean data. If None, will attempt to use
@@ -1385,65 +1386,11 @@ def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None,
13851386
if path_or_buf is None:
13861387
return formatter.path_or_buf.getvalue()
13871388

1389+
@Appender(_shared_docs['to_excel'] % _shared_doc_kwargs)
13881390
def to_excel(self, excel_writer, sheet_name='Sheet1', na_rep='',
13891391
float_format=None, columns=None, header=True, index=True,
13901392
index_label=None, startrow=0, startcol=0, engine=None,
13911393
merge_cells=True, encoding=None, inf_rep='inf', verbose=True):
1392-
"""
1393-
Write DataFrame to a excel sheet
1394-
1395-
Parameters
1396-
----------
1397-
excel_writer : string or ExcelWriter object
1398-
File path or existing ExcelWriter
1399-
sheet_name : string, default 'Sheet1'
1400-
Name of sheet which will contain DataFrame
1401-
na_rep : string, default ''
1402-
Missing data representation
1403-
float_format : string, default None
1404-
Format string for floating point numbers
1405-
columns : sequence, optional
1406-
Columns to write
1407-
header : boolean or list of string, default True
1408-
Write out column names. If a list of string is given it is
1409-
assumed to be aliases for the column names
1410-
index : boolean, default True
1411-
Write row names (index)
1412-
index_label : string or sequence, default None
1413-
Column label for index column(s) if desired. If None is given, and
1414-
`header` and `index` are True, then the index names are used. A
1415-
sequence should be given if the DataFrame uses MultiIndex.
1416-
startrow :
1417-
upper left cell row to dump data frame
1418-
startcol :
1419-
upper left cell column to dump data frame
1420-
engine : string, default None
1421-
write engine to use - you can also set this via the options
1422-
``io.excel.xlsx.writer``, ``io.excel.xls.writer``, and
1423-
``io.excel.xlsm.writer``.
1424-
merge_cells : boolean, default True
1425-
Write MultiIndex and Hierarchical Rows as merged cells.
1426-
encoding: string, default None
1427-
encoding of the resulting excel file. Only necessary for xlwt,
1428-
other writers support unicode natively.
1429-
inf_rep : string, default 'inf'
1430-
Representation for infinity (there is no native representation for
1431-
infinity in Excel)
1432-
1433-
Notes
1434-
-----
1435-
If passing an existing ExcelWriter object, then the sheet will be added
1436-
to the existing workbook. This can be used to save different
1437-
DataFrames to one workbook:
1438-
1439-
>>> writer = ExcelWriter('output.xlsx')
1440-
>>> df1.to_excel(writer,'Sheet1')
1441-
>>> df2.to_excel(writer,'Sheet2')
1442-
>>> writer.save()
1443-
1444-
For compatibility with to_csv, to_excel serializes lists and dicts to
1445-
strings before writing.
1446-
"""
14471394
from pandas.io.excel import ExcelWriter
14481395
need_save = False
14491396
if encoding is None:

pandas/core/generic.py

+58
Original file line numberDiff line numberDiff line change
@@ -1016,6 +1016,64 @@ def __setstate__(self, state):
10161016
# ----------------------------------------------------------------------
10171017
# I/O Methods
10181018

1019+
_shared_docs['to_excel'] = """
1020+
Write %(klass)s to a excel sheet
1021+
1022+
%(versionadded_to_excel)s
1023+
1024+
Parameters
1025+
----------
1026+
excel_writer : string or ExcelWriter object
1027+
File path or existing ExcelWriter
1028+
sheet_name : string, default 'Sheet1'
1029+
Name of sheet which will contain DataFrame
1030+
na_rep : string, default ''
1031+
Missing data representation
1032+
float_format : string, default None
1033+
Format string for floating point numbers
1034+
columns : sequence, optional
1035+
Columns to write
1036+
header : boolean or list of string, default True
1037+
Write out column names. If a list of string is given it is
1038+
assumed to be aliases for the column names
1039+
index : boolean, default True
1040+
Write row names (index)
1041+
index_label : string or sequence, default None
1042+
Column label for index column(s) if desired. If None is given, and
1043+
`header` and `index` are True, then the index names are used. A
1044+
sequence should be given if the DataFrame uses MultiIndex.
1045+
startrow :
1046+
upper left cell row to dump data frame
1047+
startcol :
1048+
upper left cell column to dump data frame
1049+
engine : string, default None
1050+
write engine to use - you can also set this via the options
1051+
``io.excel.xlsx.writer``, ``io.excel.xls.writer``, and
1052+
``io.excel.xlsm.writer``.
1053+
merge_cells : boolean, default True
1054+
Write MultiIndex and Hierarchical Rows as merged cells.
1055+
encoding: string, default None
1056+
encoding of the resulting excel file. Only necessary for xlwt,
1057+
other writers support unicode natively.
1058+
inf_rep : string, default 'inf'
1059+
Representation for infinity (there is no native representation for
1060+
infinity in Excel)
1061+
1062+
Notes
1063+
-----
1064+
If passing an existing ExcelWriter object, then the sheet will be added
1065+
to the existing workbook. This can be used to save different
1066+
DataFrames to one workbook:
1067+
1068+
>>> writer = ExcelWriter('output.xlsx')
1069+
>>> df1.to_excel(writer,'Sheet1')
1070+
>>> df2.to_excel(writer,'Sheet2')
1071+
>>> writer.save()
1072+
1073+
For compatibility with to_csv, to_excel serializes lists and dicts to
1074+
strings before writing.
1075+
"""
1076+
10191077
def to_json(self, path_or_buf=None, orient=None, date_format='epoch',
10201078
double_precision=10, force_ascii=True, date_unit='ms',
10211079
default_handler=None, lines=False):

pandas/core/series.py

+15-1
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,8 @@
8080
inplace="""inplace : boolean, default False
8181
If True, performs operation inplace and returns None.""",
8282
unique='np.ndarray', duplicated='Series',
83-
optional_by='')
83+
optional_by='',
84+
versionadded_to_excel='.. versionadded:: 0.20.0')
8485

8586

8687
def _coerce_method(converter):
@@ -2619,6 +2620,19 @@ def to_csv(self, path=None, index=True, sep=",", na_rep='',
26192620
if path is None:
26202621
return result
26212622

2623+
@Appender(generic._shared_docs['to_excel'] % _shared_doc_kwargs)
2624+
def to_excel(self, excel_writer, sheet_name='Sheet1', na_rep='',
2625+
float_format=None, columns=None, header=True, index=True,
2626+
index_label=None, startrow=0, startcol=0, engine=None,
2627+
merge_cells=True, encoding=None, inf_rep='inf', verbose=True):
2628+
df = self.to_frame()
2629+
df.to_excel(excel_writer=excel_writer, sheet_name=sheet_name,
2630+
na_rep=na_rep, float_format=float_format, columns=columns,
2631+
header=header, index=index, index_label=index_label,
2632+
startrow=startrow, startcol=startcol, engine=engine,
2633+
merge_cells=merge_cells, encoding=encoding,
2634+
inf_rep=inf_rep, verbose=verbose)
2635+
26222636
def dropna(self, axis=0, inplace=False, **kwargs):
26232637
"""
26242638
Return Series without null values

pandas/io/tests/test_excel.py

+6
Original file line numberDiff line numberDiff line change
@@ -1078,6 +1078,12 @@ def test_roundtrip(self):
10781078
recons = read_excel(path, index_col=0)
10791079
tm.assert_frame_equal(self.frame, recons)
10801080

1081+
# GH 8825 Pandas Series should provide to_excel method
1082+
s = self.frame["A"]
1083+
s.to_excel(path)
1084+
recons = read_excel(path, index_col=0)
1085+
tm.assert_frame_equal(s.to_frame(), recons)
1086+
10811087
def test_mixed(self):
10821088
_skip_if_no_xlrd()
10831089

0 commit comments

Comments
 (0)