Skip to content

Commit 08b9c1b

Browse files
authored
ENH: Add index option to_markdown() (#33091)
1 parent 28810c4 commit 08b9c1b

File tree

4 files changed

+61
-3
lines changed

4 files changed

+61
-3
lines changed

doc/source/whatsnew/v1.1.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,7 @@ Other enhancements
335335
- :meth:`DataFrame.to_html` and :meth:`DataFrame.to_string`'s ``col_space`` parameter now accepts a list or dict to change only some specific columns' width (:issue:`28917`).
336336
- :meth:`DataFrame.to_excel` can now also write OpenOffice spreadsheet (.ods) files (:issue:`27222`)
337337
- :meth:`~Series.explode` now accepts ``ignore_index`` to reset the index, similarly to :meth:`pd.concat` or :meth:`DataFrame.sort_values` (:issue:`34932`).
338+
- :meth:`DataFrame.to_markdown` and :meth:`Series.to_markdown` now accept ``index`` argument as an alias for tabulate's ``showindex`` (:issue:`32667`)
338339
- :meth:`read_csv` now accepts string values like "0", "0.0", "1", "1.0" as convertible to the nullable boolean dtype (:issue:`34859`)
339340
- :class:`pandas.core.window.ExponentialMovingWindow` now supports a ``times`` argument that allows ``mean`` to be calculated with observations spaced by the timestamps in ``times`` (:issue:`34839`)
340341
- :meth:`DataFrame.agg` and :meth:`Series.agg` now accept named aggregation for renaming the output columns/indexes. (:issue:`26513`)

pandas/core/frame.py

+14-1
Original file line numberDiff line numberDiff line change
@@ -2236,10 +2236,23 @@ def to_feather(self, path, **kwargs) -> None:
22362236
""",
22372237
)
22382238
def to_markdown(
2239-
self, buf: Optional[IO[str]] = None, mode: Optional[str] = None, **kwargs
2239+
self,
2240+
buf: Optional[IO[str]] = None,
2241+
mode: Optional[str] = None,
2242+
index: bool = True,
2243+
**kwargs,
22402244
) -> Optional[str]:
2245+
if "showindex" in kwargs:
2246+
warnings.warn(
2247+
"'showindex' is deprecated. Only 'index' will be used "
2248+
"in a future version. Use 'index' to silence this warning.",
2249+
FutureWarning,
2250+
stacklevel=2,
2251+
)
2252+
22412253
kwargs.setdefault("headers", "keys")
22422254
kwargs.setdefault("tablefmt", "pipe")
2255+
kwargs.setdefault("showindex", index)
22432256
tabulate = import_optional_dependency("tabulate")
22442257
result = tabulate.tabulate(self, **kwargs)
22452258
if buf is None:

pandas/core/series.py

+11-2
Original file line numberDiff line numberDiff line change
@@ -1419,7 +1419,11 @@ def to_string(
14191419
),
14201420
)
14211421
def to_markdown(
1422-
self, buf: Optional[IO[str]] = None, mode: Optional[str] = None, **kwargs
1422+
self,
1423+
buf: Optional[IO[str]] = None,
1424+
mode: Optional[str] = None,
1425+
index: bool = True,
1426+
**kwargs,
14231427
) -> Optional[str]:
14241428
"""
14251429
Print {klass} in Markdown-friendly format.
@@ -1432,6 +1436,11 @@ def to_markdown(
14321436
Buffer to write to. If None, the output is returned as a string.
14331437
mode : str, optional
14341438
Mode in which file is opened.
1439+
index : bool, optional, default True
1440+
Add index (row) labels.
1441+
1442+
.. versionadded:: 1.1.0
1443+
14351444
**kwargs
14361445
These parameters will be passed to `tabulate \
14371446
<https://pypi.org/project/tabulate>`_.
@@ -1467,7 +1476,7 @@ def to_markdown(
14671476
| 3 | quetzal |
14681477
+----+----------+
14691478
"""
1470-
return self.to_frame().to_markdown(buf, mode, **kwargs)
1479+
return self.to_frame().to_markdown(buf, mode, index, **kwargs)
14711480

14721481
# ----------------------------------------------------------------------
14731482

pandas/tests/io/formats/test_to_markdown.py

+35
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import pytest
44

55
import pandas as pd
6+
import pandas._testing as tm
67

78
pytest.importorskip("tabulate")
89

@@ -53,3 +54,37 @@ def test_no_buf(capsys):
5354
assert (
5455
result == "| | 0 |\n|---:|----:|\n| 0 | 1 |\n| 1 | 2 |\n| 2 | 3 |"
5556
)
57+
58+
59+
@pytest.mark.parametrize("index", [True, False, None])
60+
@pytest.mark.parametrize("showindex", [True, False, None])
61+
def test_index(index, showindex):
62+
# GH 32667
63+
kwargs = {}
64+
if index is not None:
65+
kwargs["index"] = index
66+
if showindex is not None:
67+
kwargs["showindex"] = showindex
68+
69+
df = pd.DataFrame([1, 2, 3])
70+
yes_index_result = (
71+
"| | 0 |\n|---:|----:|\n| 0 | 1 |\n| 1 | 2 |\n| 2 | 3 |"
72+
)
73+
no_index_result = "| 0 |\n|----:|\n| 1 |\n| 2 |\n| 3 |"
74+
75+
warning = FutureWarning if "showindex" in kwargs else None
76+
with tm.assert_produces_warning(warning):
77+
result = df.to_markdown(**kwargs)
78+
79+
if "showindex" in kwargs:
80+
# give showindex higher priority if specified
81+
if showindex:
82+
expected = yes_index_result
83+
else:
84+
expected = no_index_result
85+
else:
86+
if index in [True, None]:
87+
expected = yes_index_result
88+
else:
89+
expected = no_index_result
90+
assert result == expected

0 commit comments

Comments
 (0)