Skip to content

Commit

Permalink
👌 return string if buf is set to None, use shared doc, change version…
Browse files Browse the repository at this point in the history
… introduced in to 1.0.0
  • Loading branch information
MarcoGorelli committed Dec 21, 2019
1 parent 474a354 commit a572e29
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 45 deletions.
39 changes: 19 additions & 20 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -1966,31 +1966,30 @@ def to_feather(self, path):

to_feather(self, path)

def to_markdown(
self,
buf: Optional[FilePathOrBuffer[str]] = None,
mode: Optional[str] = None,
**kwargs,
) -> None:
@Appender(
"""
Print a DataFrame in Markdown-friendly format.
.. versionadded:: 1.0
Returns
-------
str
DataFrame in Markdown-friendly format.
Examples
--------
>>> df = pd.DataFrame(data={'col1': [1, 2], 'col2': [3, 4]})
>>> df = pd.DataFrame(
... data={"animal_1": ["elk", "pig"], "animal_2": ["dog", "quetzal"]}
... )
>>> print(df.to_markdown())
| | col1 | col2 |
|---:|-------:|-------:|
| 0 | 1 | 3 |
| 1 | 2 | 4 |
| | animal_1 | animal_2 |
|---:|:-----------|:-----------|
| 0 | elk | dog |
| 1 | pig | quetzal |
"""
)
@Substitution(klass="DataFrame")
@Appender(_shared_docs["to_markdown"])
def to_markdown(
self,
buf: Optional[FilePathOrBuffer[str]] = None,
mode: Optional[str] = None,
**kwargs,
) -> Optional[str]:
kwargs.setdefault("headers", "keys")
kwargs.setdefault("tablefmt", "pipe")
tabulate = import_optional_dependency("tabulate")
result = tabulate.tabulate(self, **kwargs)
if buf is None:
Expand Down
21 changes: 21 additions & 0 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -2009,6 +2009,27 @@ def _repr_data_resource_(self):
# ----------------------------------------------------------------------
# I/O Methods

_shared_docs[
"to_markdown"
] = """
Print %(klass)s in Markdown-friendly format.
.. versionadded:: 1.0.0
Parameters
----------
buf : writable buffer, defaults to sys.stdout
Where to send the output. By default, the output is printed to
sys.stdout. Pass a writable buffer if you need to further process
the output.
mode : str, optional
Returns
-------
str
%(klass)s in Markdown-friendly format.
"""

_shared_docs[
"to_excel"
] = """
Expand Down
40 changes: 18 additions & 22 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
is_empty_data,
sanitize_array,
)
from pandas.core.generic import _shared_docs
from pandas.core.indexers import maybe_convert_indices
from pandas.core.indexes.accessors import CombinedDatetimelikeProperties
from pandas.core.indexes.api import (
Expand Down Expand Up @@ -1435,33 +1436,28 @@ def to_string(
with open(buf, "w") as f:
f.write(result)

def to_markdown(
self,
buf: Optional[FilePathOrBuffer[str]] = None,
mode: Optional[str] = None,
**kwargs,
) -> str:
@Appender(
"""
Print a Series in Markdown-friendly format.
.. versionadded:: 1.0
Returns
-------
str
Series in Markdown-friendly format.
Examples
--------
>>> s = pd.Series([1, 2, 3, 4])
>>> s = pd.Series(["elk", "pig", "dog", "quetzal"], name="animal")
>>> print(s.to_markdown())
| | 0 |
|---:|----:|
| 0 | 1 |
| 1 | 2 |
| 2 | 3 |
| 3 | 4 |
| | animal |
|---:|:---------|
| 0 | elk |
| 1 | pig |
| 2 | dog |
| 3 | quetzal |
"""
)
@Substitution(klass="Series")
@Appender(_shared_docs["to_markdown"])
def to_markdown(
self,
buf: Optional[FilePathOrBuffer[str]] = None,
mode: Optional[str] = None,
**kwargs,
) -> Optional[str]:
return self.to_frame().to_markdown(buf, mode, **kwargs)

# ----------------------------------------------------------------------
Expand Down
7 changes: 4 additions & 3 deletions pandas/tests/io/formats/test_to_markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ def test_series():

def test_no_buf(capsys):
df = pd.DataFrame([1, 2, 3])
df.to_markdown()
out, _ = capsys.readouterr()
assert out == "| | 0 |\n|---:|----:|\n| 0 | 1 |\n| 1 | 2 |\n| 2 | 3 |"
result = df.to_markdown()
assert (
result == "| | 0 |\n|---:|----:|\n| 0 | 1 |\n| 1 | 2 |\n| 2 | 3 |"
)

0 comments on commit a572e29

Please sign in to comment.