Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -750,6 +750,7 @@ I/O
- :meth:`DataFrame.to_csv` was re-opening file-like handles that also implement ``os.PathLike`` (:issue:`38125`)
- Bug in the conversion of a sliced ``pyarrow.Table`` with missing values to a DataFrame (:issue:`38525`)
- Bug in :func:`read_sql_table` raising a ``sqlalchemy.exc.OperationalError`` when column names contained a percentage sign (:issue:`37517`)
- :class:`DataFrameFormatter` was using the full list of columns when computing formatters for truncated displays (:issue:`35907`)

Period
^^^^^^
Expand Down
2 changes: 1 addition & 1 deletion pandas/io/formats/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -840,7 +840,7 @@ def _get_formatter(self, i: Union[str, int]) -> Optional[Callable]:
return None
else:
if is_integer(i) and i not in self.columns:
i = self.columns[i]
i = self.tr_frame.columns[i]
return self.formatters.get(i, None)

def _get_formatted_column_labels(self, frame: DataFrame) -> List[List[str]]:
Expand Down
29 changes: 29 additions & 0 deletions pandas/tests/io/formats/test_to_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,35 @@ def test_to_string_with_formatters():
assert result == result2


@pytest.mark.parametrize(
"formatters",
[
{
"int": lambda x: f"[1] {x}",
"float": lambda x: f"[2] {x}",
"object": lambda x: f"[3] {x}",
},
[lambda x: f"[1] {x}", lambda x: f"[2] {x}", lambda x: f"[3] {x}"],
],
)
def test_to_string_with_truncated_formatters(formatters):
df = DataFrame(
{
"int": [1, 2, 3],
"float": [1.0, 2.0, 3.0],
"object": [(1, 2), True, False],
},
columns=["int", "float", "object"],
)
result = df.to_string(formatters=formatters, max_cols=2)
assert result == (
" int ... object\n"
"0 [1] 1 ... [3] (1, 2)\n"
"1 [1] 2 ... [3] True\n"
"2 [1] 3 ... [3] False"
)


def test_to_string_with_datetime64_monthformatter():
months = [datetime(2016, 1, 1), datetime(2016, 2, 2)]
x = DataFrame({"months": months})
Expand Down