Skip to content

Allow reading SAS files from archives #47154

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 9 commits into from
Jun 15, 2022
Merged
Show file tree
Hide file tree
Changes from 6 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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ Other enhancements
- ``times`` argument in :class:`.ExponentialMovingWindow` now accepts ``np.timedelta64`` (:issue:`47003`)
- :class:`DataError`, :class:`SpecificationError`, :class:`SettingWithCopyError`, :class:`SettingWithCopyWarning`, and :class:`NumExprClobberingError` are now exposed in ``pandas.errors`` (:issue:`27656`)
- Added ``check_like`` argument to :func:`testing.assert_series_equal` (:issue:`47247`)
- Allow reading compressed SAS files with :func:`read_sas` (e.g., ``.sas7bdat.gz`` files)

.. ---------------------------------------------------------------------------
.. _whatsnew_150.notable_bug_fixes:
Expand Down
6 changes: 5 additions & 1 deletion pandas/io/sas/sas7bdat.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import numpy as np

from pandas._typing import (
CompressionOptions,
FilePath,
ReadBuffer,
)
Expand Down Expand Up @@ -168,6 +169,7 @@ def __init__(
encoding=None,
convert_text=True,
convert_header_text=True,
compression: CompressionOptions = "infer",
) -> None:

self.index = index
Expand Down Expand Up @@ -195,7 +197,9 @@ def __init__(
self._current_row_on_page_index = 0
self._current_row_in_file_index = 0

self.handles = get_handle(path_or_buf, "rb", is_text=False)
self.handles = get_handle(
path_or_buf, "rb", is_text=False, compression=compression
)

self._path_or_buf = self.handles.handle

Expand Down
8 changes: 7 additions & 1 deletion pandas/io/sas/sas_xport.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import numpy as np

from pandas._typing import (
CompressionOptions,
DatetimeNaTType,
FilePath,
ReadBuffer,
Expand Down Expand Up @@ -256,6 +257,7 @@ def __init__(
index=None,
encoding: str | None = "ISO-8859-1",
chunksize=None,
compression: CompressionOptions = "infer",
) -> None:

self._encoding = encoding
Expand All @@ -264,7 +266,11 @@ def __init__(
self._chunksize = chunksize

self.handles = get_handle(
filepath_or_buffer, "rb", encoding=encoding, is_text=False
filepath_or_buffer,
"rb",
encoding=encoding,
is_text=False,
compression=compression,
)
self.filepath_or_buffer = self.handles.handle

Expand Down
25 changes: 22 additions & 3 deletions pandas/io/sas/sasreader.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,16 @@
)

from pandas._typing import (
CompressionOptions,
FilePath,
ReadBuffer,
)
from pandas.util._decorators import (
Substitution,
deprecate_nonkeyword_arguments,
)

from pandas.core.shared_docs import _shared_docs

from pandas.io.common import stringify_path

Expand Down Expand Up @@ -53,6 +60,7 @@ def read_sas(
encoding: str | None = ...,
chunksize: int = ...,
iterator: bool = ...,
compression: CompressionOptions = ...,
) -> ReaderBase:
...

Expand All @@ -65,17 +73,23 @@ def read_sas(
encoding: str | None = ...,
chunksize: None = ...,
iterator: bool = ...,
compression: CompressionOptions = ...,
) -> DataFrame | ReaderBase:
...


@deprecate_nonkeyword_arguments(
version=None, allowed_args=["filepath_or_buffer"], stacklevel=2
)
@Substitution(decompression_options=_shared_docs["decompression_options"])
def read_sas(
filepath_or_buffer: FilePath | ReadBuffer[bytes],
format: str | None = None,
index: Hashable | None = None,
encoding: str | None = None,
chunksize: int | None = None,
iterator: bool = False,
compression: CompressionOptions = "infer",
) -> DataFrame | ReaderBase:
"""
Read SAS files stored as either XPORT or SAS7BDAT format files.
Expand Down Expand Up @@ -107,6 +121,7 @@ def read_sas(
.. versionchanged:: 1.2

``TextFileReader`` is a context manager.
%(decompression_options)s
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No indent here for the %(...)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See question in other comment thread. I think your suggestion is wrong.


Returns
-------
Expand All @@ -122,12 +137,14 @@ def read_sas(
if not isinstance(filepath_or_buffer, str):
raise ValueError(buffer_error_msg)
fname = filepath_or_buffer.lower()
if fname.endswith(".xpt"):
if ".xpt" in fname:
format = "xport"
elif fname.endswith(".sas7bdat"):
elif ".sas7bdat" in fname:
format = "sas7bdat"
else:
raise ValueError("unable to infer format of SAS file")
raise ValueError(
f"unable to infer format of SAS file from filename: {repr(fname)}"
)

reader: ReaderBase
if format.lower() == "xport":
Expand All @@ -138,6 +155,7 @@ def read_sas(
index=index,
encoding=encoding,
chunksize=chunksize,
compression=compression,
)
elif format.lower() == "sas7bdat":
from pandas.io.sas.sas7bdat import SAS7BDATReader
Expand All @@ -147,6 +165,7 @@ def read_sas(
index=index,
encoding=encoding,
chunksize=chunksize,
compression=compression,
)
else:
raise ValueError("unknown SAS format")
Expand Down
Binary file added pandas/tests/io/sas/data/airline.sas7bdat.gz
Binary file not shown.
10 changes: 9 additions & 1 deletion pandas/tests/io/sas/test_sas.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,15 @@ def test_sas_buffer_format(self):

def test_sas_read_no_format_or_extension(self):
# see gh-24548
msg = "unable to infer format of SAS file"
msg = "unable to infer format of SAS file.+"
with tm.ensure_clean("test_file_no_extension") as path:
with pytest.raises(ValueError, match=msg):
read_sas(path)


def test_sas_archive(datapath):
fname_uncompressed = datapath("io", "sas", "data", "airline.sas7bdat")
df_uncompressed = read_sas(fname_uncompressed)
fname_compressed = datapath("io", "sas", "data", "airline.sas7bdat.gz")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is worth adding a gzip'd file? Could the gzip file be created on the fly during the test? This would also let you test other supported formats, e.g., zip

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We do have .gz files in the repo so I thought that's the way to go. Can also gzip the file in the test. Let me know what's your preference.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it is essential to use this method - I just wonder about the longer term future since it isn't strictly necessary to add compressed versions of files to the main repo. I'm happy to sign off on it as it is now.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My 2c. I would prefer these files to by gzipped on the fly in the test such that files in the main repo are absolutely necessary. Doesn't have to be for this PR but a followup would be appreciated

df_compressed = read_sas(fname_compressed, format="sas7bdat")
tm.assert_frame_equal(df_uncompressed, df_compressed)