Skip to content

Make to_csv return a string if no path or buffer is provided. #6406

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 9, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/source/release.rst
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ API Changes
- ``df['col'] = value`` and ``df.loc[:,'col'] = value`` are now completely equivalent;
previously the ``.loc`` would not necessarily coerce the dtype of the resultant series (:issue:`6149`)
- ``dtypes`` and ``ftypes`` now return a series with ``dtype=object`` on empty containers (:issue:`5740`)
- ``df.to_csv`` will now return a string of the CSV data if neither a target path nor a buffer is provided
(:issue:`6061`)
- The ``interpolate`` ``downcast`` keyword default has been changed from ``infer`` to
``None``. This is to preseve the original dtype unless explicitly requested otherwise (:issue:`6290`).
- allow a Series to utilize index methods depending on its index type, e.g. ``Series.year`` is now defined
Expand Down
7 changes: 5 additions & 2 deletions pandas/core/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -943,7 +943,7 @@ def grouper(x):

class CSVFormatter(object):

def __init__(self, obj, path_or_buf, sep=",", na_rep='', float_format=None,
def __init__(self, obj, path_or_buf=None, sep=",", na_rep='', float_format=None,
cols=None, header=True, index=True, index_label=None,
mode='w', nanRep=None, encoding=None, quoting=None,
line_terminator='\n', chunksize=None, engine=None,
Expand All @@ -953,6 +953,9 @@ def __init__(self, obj, path_or_buf, sep=",", na_rep='', float_format=None,
self.engine = engine # remove for 0.13
self.obj = obj

if path_or_buf is None:
path_or_buf = StringIO()

self.path_or_buf = path_or_buf
self.sep = sep
self.na_rep = na_rep
Expand Down Expand Up @@ -1144,7 +1147,7 @@ def strftime_with_nulls(x):

def save(self):
# create the writer & save
if hasattr(self.path_or_buf, 'read'):
if hasattr(self.path_or_buf, 'write'):
f = self.path_or_buf
close = False
else:
Expand Down
10 changes: 7 additions & 3 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -1067,7 +1067,7 @@ def to_panel(self):

to_wide = deprecate('to_wide', to_panel)

def to_csv(self, path_or_buf, sep=",", na_rep='', float_format=None,
def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None,
cols=None, header=True, index=True, index_label=None,
mode='w', nanRep=None, encoding=None, quoting=None,
quotechar='"', line_terminator='\n', chunksize=None,
Expand All @@ -1077,8 +1077,9 @@ def to_csv(self, path_or_buf, sep=",", na_rep='', float_format=None,

Parameters
----------
path_or_buf : string or file handle / StringIO
File path
path_or_buf : string or file handle, default None
File path or object, if None is provided the result is returned as
a string.
sep : character, default ","
Field delimiter for the output file.
na_rep : string, default ''
Expand Down Expand Up @@ -1144,6 +1145,9 @@ def to_csv(self, path_or_buf, sep=",", na_rep='', float_format=None,
escapechar=escapechar)
formatter.save()

if path_or_buf is None:
return formatter.path_or_buf.getvalue()

def to_excel(self, excel_writer, sheet_name='Sheet1', na_rep='',
float_format=None, cols=None, header=True, index=True,
index_label=None, startrow=0, startcol=0, engine=None,
Expand Down
6 changes: 6 additions & 0 deletions pandas/tests/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -1787,6 +1787,12 @@ def test_to_csv_escapechar(self):
with open(path, 'r') as f:
self.assertEqual(f.read(), expected)

def test_csv_to_string(self):
df = DataFrame({'col' : [1,2]})
expected = ',col\n0,1\n1,2\n'
self.assertEqual(df.to_csv(), expected)


class TestSeriesFormatting(tm.TestCase):
_multiprocess_can_split_ = True

Expand Down