Skip to content

BUG: StataWriter value_label encoding #47199

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -820,7 +820,7 @@ I/O
- Bug in :func:`read_parquet` when ``engine="fastparquet"`` where the file was not closed on error (:issue:`46555`)
- :meth:`to_html` now excludes the ``border`` attribute from ``<table>`` elements when ``border`` keyword is set to ``False``.
- Bug in :func:`read_sas` returned ``None`` rather than an empty DataFrame for SAS7BDAT files with zero rows (:issue:`18198`)
-
- Bug in :class:`StataWriter` where value labels were always written with default encoding (:issue:`46750`)

Period
^^^^^^
Expand Down
10 changes: 6 additions & 4 deletions pandas/io/stata.py
Original file line number Diff line number Diff line change
Expand Up @@ -668,7 +668,9 @@ class StataValueLabel:
Encoding to use for value labels.
"""

def __init__(self, catarray: Series, encoding: str = "latin-1") -> None:
def __init__(
self, catarray: Series, encoding: Literal["latin-1", "utf-8"] = "latin-1"
) -> None:

if encoding not in ("latin-1", "utf-8"):
raise ValueError("Only latin-1 and utf-8 are supported.")
Expand Down Expand Up @@ -2250,7 +2252,7 @@ class StataWriter(StataParser):
"""

_max_string_length = 244
_encoding = "latin-1"
_encoding: Literal["latin-1", "utf-8"] = "latin-1"

def __init__(
self,
Expand Down Expand Up @@ -2331,7 +2333,7 @@ def _prepare_non_cat_value_labels(
f"Can't create value labels for {labname}, value labels "
"can only be applied to numeric columns."
)
svl = StataNonCatValueLabel(colname, labels)
svl = StataNonCatValueLabel(colname, labels, self._encoding)
non_cat_value_labels.append(svl)
return non_cat_value_labels

Expand Down Expand Up @@ -3575,7 +3577,7 @@ class StataWriterUTF8(StataWriter117):
>>> writer.write_file()
"""

_encoding = "utf-8"
_encoding: Literal["utf-8"] = "utf-8"

def __init__(
self,
Expand Down
6 changes: 6 additions & 0 deletions pandas/tests/io/test_stata.py
Original file line number Diff line number Diff line change
Expand Up @@ -1797,6 +1797,7 @@ def test_utf8_writer(self, version):
"ᴐᴬᵀ": "",
}
data_label = "ᴅaᵀa-label"
value_labels = {"β": {1: "label", 2: "æøå", 3: "ŋot valid latin-1"}}
data["β"] = data["β"].astype(np.int32)
with tm.ensure_clean() as path:
writer = StataWriterUTF8(
Expand All @@ -1807,11 +1808,16 @@ def test_utf8_writer(self, version):
variable_labels=variable_labels,
write_index=False,
version=version,
value_labels=value_labels,
)
writer.write_file()
reread_encoded = read_stata(path)
# Missing is intentionally converted to empty strl
data["strls"] = data["strls"].fillna("")
# Variable with value labels is reread as categorical
data["β"] = (
data["β"].replace(value_labels["β"]).astype("category").cat.as_ordered()
)
tm.assert_frame_equal(data, reread_encoded)
reader = StataReader(path)
assert reader.data_label == data_label
Expand Down