Skip to content

Commit cdb3fa9

Browse files
Marco GorelliMarcoGorelli
authored andcommitted
✨ add buf and mode arguments to to_markdown
1 parent cdc4d50 commit cdb3fa9

File tree

2 files changed

+22
-8
lines changed

2 files changed

+22
-8
lines changed

pandas/core/frame.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,7 @@
119119
from pandas.core.ops.missing import dispatch_fill_zeros
120120
from pandas.core.series import Series
121121

122+
from pandas.io.common import get_filepath_or_buffer
122123
from pandas.io.formats import console, format as fmt
123124
from pandas.io.formats.printing import pprint_thing
124125
import pandas.plotting
@@ -1965,7 +1966,12 @@ def to_feather(self, path):
19651966

19661967
to_feather(self, path)
19671968

1968-
def to_markdown(self, **kwargs):
1969+
def to_markdown(
1970+
self,
1971+
buf: Optional[FilePathOrBuffer[str]] = None,
1972+
mode: Optional[str] = None,
1973+
**kwargs,
1974+
) -> None:
19691975
"""
19701976
Print a DataFrame in markdown-friendly format.
19711977
@@ -1985,12 +1991,14 @@ def to_markdown(self, **kwargs):
19851991
| 0 | 1 | 3 |
19861992
| 1 | 2 | 4 |
19871993
"""
1994+
if buf is None:
1995+
buf = sys.stdout
1996+
1997+
buf, _, _, _ = get_filepath_or_buffer(buf, mode=mode)
19881998
tabulate = import_optional_dependency("tabulate")
1989-
if "headers" not in kwargs:
1990-
kwargs["headers"] = "keys"
1991-
if "tablefmt" not in kwargs:
1992-
kwargs["tablefmt"] = "pipe"
1993-
return tabulate.tabulate(self, **kwargs)
1999+
kwargs.setdefault("headers", "keys")
2000+
kwargs.setdefault("tablefmt", "pipe")
2001+
buf.writelines(tabulate.tabulate(self, **kwargs))
19942002

19952003
@deprecate_kwarg(old_arg_name="fname", new_arg_name="path")
19962004
def to_parquet(

pandas/core/series.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
)
4848

4949
import pandas as pd
50+
from pandas._typing import FilePathOrBuffer
5051
from pandas.core import algorithms, base, generic, nanops, ops
5152
from pandas.core.accessor import CachedAccessor
5253
from pandas.core.arrays import ExtensionArray, try_cast_to_ea
@@ -1434,7 +1435,12 @@ def to_string(
14341435
with open(buf, "w") as f:
14351436
f.write(result)
14361437

1437-
def to_markdown(self, **kwargs):
1438+
def to_markdown(
1439+
self,
1440+
buf: Optional[FilePathOrBuffer[str]] = None,
1441+
mode: Optional[str] = None,
1442+
**kwargs,
1443+
) -> str:
14381444
"""
14391445
Print a Series in markdown-friendly format.
14401446
@@ -1456,7 +1462,7 @@ def to_markdown(self, **kwargs):
14561462
| 2 | 3 |
14571463
| 3 | 4 |
14581464
"""
1459-
return self.to_frame().to_markdown(**kwargs)
1465+
return self.to_frame().to_markdown(buf, mode, **kwargs)
14601466

14611467
# ----------------------------------------------------------------------
14621468

0 commit comments

Comments
 (0)