Skip to content

[BUG] adorn_pct_formatting, adorn_ns and adorn_rounding overwrite a numeric first column #1676

Description

@dylanpulver

Brief Description

adorn_pct_formatting, adorn_ns and adorn_rounding treat a numeric first column as data, so the row labels of a tabyl get overwritten.

Using the cyl/gear shape from tests/functions/test_tabyl.py:

basic_df.tabyl("cyl", "gear").adorn_percentages("row").adorn_pct_formatting()

returns cyl as ['400.0%', '600.0%', '800.0%'] instead of [4, 6, 8].

With a counts frame whose first column is year = [2020, 2021]:

call year becomes expected
adorn_pct_formatting() ['202000.0%', '202100.0%'] [2020, 2021]
adorn_ns() ['202000.0% (2,020)', '202100.0% (2,021)'] [2020, 2021]
adorn_rounding(digits=2) [2020.0, 2021.0], int64 becomes float64 [2020, 2021]

adorn_totals and adorn_percentages exclude the first column, and the docstrings of test_adorn_totals_numeric_first_column and test_adorn_percentages_numeric_first_column state that the first column is "always treated as a row identifier (consistent with R janitor tabyl behavior)". The three functions above disagree with that.

A string first column is unaffected.

System Information

  • Operating system: macOS
  • OS details (optional): 26.5.1, arm64
  • Python version (required): 3.12.13

pandas 3.0.5, pyjanitor dev at 6edcbdc.

Minimally Reproducible Code

import pandas as pd
import janitor  # noqa: F401

df = pd.DataFrame(
    {"cyl": [4, 6, 8, 4, 6, 8, 4, 6], "gear": [3, 3, 3, 4, 4, 4, 5, 5]}
)
print(df.tabyl("cyl", "gear").adorn_percentages("row").adorn_pct_formatting())

counts = pd.DataFrame({"year": [2020, 2021], "yes": [10, 20], "no": [5, 15]})
pct = counts.adorn_percentages("row")  # year is correctly left alone here
print(pct.adorn_pct_formatting())
print(pct.adorn_pct_formatting().adorn_ns())
print(pct.adorn_rounding(digits=2))

Error Messages

No exception is raised. The output is silently wrong:

      cyl      3      4      5
0  400.0%  33.3%  33.3%  33.3%
1  600.0%  33.3%  33.3%  33.3%
2  800.0%  50.0%  50.0%   0.0%

        year    yes     no
0  202000.0%  66.7%  33.3%
1  202100.0%  57.1%  42.9%

                year         yes          no
0  202000.0% (2,020)  66.7% (10)   33.3% (5)
1  202100.0% (2,021)  57.1% (20)  42.9% (15)

     year   yes    no
0  2020.0  0.67  0.33
1  2021.0  0.57  0.43

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions