Skip to content

Commit b3dd9ba

Browse files
scls19frjorisvandenbossche
scls19fr
authored andcommitted
ENH: add Series to_excel method (#14780)
Closes #8825
1 parent b97e007 commit b3dd9ba

File tree

6 files changed

+83
-59
lines changed

6 files changed

+83
-59
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

+2-2
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,8 @@ Other enhancements
5050
- ``Series.sort_index`` accepts parameters ``kind`` and ``na_position`` (:issue:`13589`, :issue:`14444`)
5151

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

5656
.. _whatsnew_0200.api_breaking:
5757

@@ -106,4 +106,4 @@ Performance Improvements
106106
.. _whatsnew_0200.bug_fixes:
107107

108108
Bug Fixes
109-
~~~~~~~~~
109+
~~~~~~~~~

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

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

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

8586

8687
def _coerce_method(converter):
@@ -2621,6 +2622,19 @@ def to_csv(self, path=None, index=True, sep=",", na_rep='',
26212622
if path is None:
26222623
return result
26232624

2625+
@Appender(generic._shared_docs['to_excel'] % _shared_doc_kwargs)
2626+
def to_excel(self, excel_writer, sheet_name='Sheet1', na_rep='',
2627+
float_format=None, columns=None, header=True, index=True,
2628+
index_label=None, startrow=0, startcol=0, engine=None,
2629+
merge_cells=True, encoding=None, inf_rep='inf', verbose=True):
2630+
df = self.to_frame()
2631+
df.to_excel(excel_writer=excel_writer, sheet_name=sheet_name,
2632+
na_rep=na_rep, float_format=float_format, columns=columns,
2633+
header=header, index=index, index_label=index_label,
2634+
startrow=startrow, startcol=startcol, engine=engine,
2635+
merge_cells=merge_cells, encoding=encoding,
2636+
inf_rep=inf_rep, verbose=verbose)
2637+
26242638
def dropna(self, axis=0, inplace=False, **kwargs):
26252639
"""
26262640
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)