-
-
Notifications
You must be signed in to change notification settings - Fork 18.3k
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
ENH(string dtype): fallback for HDF5 with UTF-8 surrogates #60993
Open
rhshadrach
wants to merge
2
commits into
pandas-dev:main
Choose a base branch
from
rhshadrach:str_hdf5_surrogates
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+96
−39
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -39,6 +39,7 @@ | |
) | ||
from pandas._libs.lib import is_string_array | ||
from pandas._libs.tslibs import timezones | ||
from pandas.compat import HAS_PYARROW | ||
from pandas.compat._optional import import_optional_dependency | ||
from pandas.compat.pickle_compat import patch_pickle | ||
from pandas.errors import ( | ||
|
@@ -376,6 +377,13 @@ def read_hdf( | |
object | ||
The selected object. Return type depends on the object stored. | ||
|
||
Notes | ||
----- | ||
When ``errors="surrogatepass"``, ``pd.options.future.infer_string`` is true, | ||
and PyArrow is installed, if a UTF-16 surrogate is encountered when decoding | ||
to UTF-8, the resulting dtype will be | ||
``pd.StringDtype(storage="python", na_value=np.nan)``. | ||
|
||
See Also | ||
-------- | ||
DataFrame.to_hdf : Write a HDF file from a DataFrame. | ||
|
@@ -2257,6 +2265,20 @@ def convert( | |
# making an Index instance could throw a number of different errors | ||
try: | ||
new_pd_index = factory(values, **kwargs) | ||
except UnicodeEncodeError as err: | ||
if ( | ||
errors == "surrogatepass" | ||
and get_option("future.infer_string") | ||
and str(err).endswith("surrogates not allowed") | ||
and HAS_PYARROW | ||
): | ||
new_pd_index = factory( | ||
values, | ||
dtype=StringDtype(storage="python", na_value=np.nan), | ||
**kwargs, | ||
) | ||
else: | ||
raise | ||
except ValueError: | ||
# if the output freq is different that what we recorded, | ||
# it should be None (see also 'doc example part 2') | ||
|
@@ -3170,12 +3192,29 @@ def read_index_node( | |
**kwargs, | ||
) | ||
else: | ||
index = factory( | ||
_unconvert_index( | ||
data, kind, encoding=self.encoding, errors=self.errors | ||
), | ||
**kwargs, | ||
) | ||
try: | ||
index = factory( | ||
_unconvert_index( | ||
data, kind, encoding=self.encoding, errors=self.errors | ||
), | ||
**kwargs, | ||
) | ||
except UnicodeEncodeError as err: | ||
if ( | ||
self.errors == "surrogatepass" | ||
and get_option("future.infer_string") | ||
and str(err).endswith("surrogates not allowed") | ||
and HAS_PYARROW | ||
): | ||
index = factory( | ||
_unconvert_index( | ||
data, kind, encoding=self.encoding, errors=self.errors | ||
), | ||
dtype=StringDtype(storage="python", na_value=np.nan), | ||
**kwargs, | ||
) | ||
else: | ||
raise | ||
|
||
index.name = name | ||
|
||
|
@@ -3311,13 +3350,24 @@ def read( | |
self.validate_read(columns, where) | ||
index = self.read_index("index", start=start, stop=stop) | ||
values = self.read_array("values", start=start, stop=stop) | ||
result = Series(values, index=index, name=self.name, copy=False) | ||
if ( | ||
using_string_dtype() | ||
and isinstance(values, np.ndarray) | ||
and is_string_array(values, skipna=True) | ||
): | ||
result = result.astype(StringDtype(na_value=np.nan)) | ||
try: | ||
result = Series(values, index=index, name=self.name, copy=False) | ||
except UnicodeEncodeError as err: | ||
if ( | ||
self.errors == "surrogatepass" | ||
and get_option("future.infer_string") | ||
and str(err).endswith("surrogates not allowed") | ||
and HAS_PYARROW | ||
): | ||
result = Series( | ||
values, | ||
index=index, | ||
name=self.name, | ||
copy=False, | ||
dtype=StringDtype(storage="python", na_value=np.nan), | ||
) | ||
else: | ||
raise | ||
return result | ||
|
||
def write(self, obj, **kwargs) -> None: | ||
|
@@ -4764,7 +4814,24 @@ def read( | |
values = values.reshape((1, values.shape[0])) | ||
|
||
if isinstance(values, (np.ndarray, DatetimeArray)): | ||
df = DataFrame(values.T, columns=cols_, index=index_, copy=False) | ||
try: | ||
df = DataFrame(values.T, columns=cols_, index=index_, copy=False) | ||
except UnicodeEncodeError as err: | ||
if ( | ||
self.errors == "surrogatepass" | ||
and get_option("future.infer_string") | ||
and str(err).endswith("surrogates not allowed") | ||
and HAS_PYARROW | ||
): | ||
df = DataFrame( | ||
values.T, | ||
columns=cols_, | ||
index=index_, | ||
copy=False, | ||
dtype=StringDtype(storage="python", na_value=np.nan), | ||
) | ||
else: | ||
raise | ||
elif isinstance(values, Index): | ||
df = DataFrame(values, columns=cols_, index=index_) | ||
else: | ||
|
@@ -4774,23 +4841,10 @@ def read( | |
assert (df.dtypes == values.dtype).all(), (df.dtypes, values.dtype) | ||
|
||
# If str / string dtype is stored in meta, use that. | ||
converted = False | ||
for column in cols_: | ||
dtype = getattr(self.table.attrs, f"{column}_meta", None) | ||
if dtype in ["str", "string"]: | ||
df[column] = df[column].astype(dtype) | ||
converted = True | ||
# Otherwise try inference. | ||
if ( | ||
not converted | ||
and using_string_dtype() | ||
and isinstance(values, np.ndarray) | ||
and is_string_array( | ||
values, | ||
skipna=True, | ||
) | ||
): | ||
df = df.astype(StringDtype(na_value=np.nan)) | ||
frames.append(df) | ||
|
||
if len(frames) == 1: | ||
|
@@ -5224,7 +5278,7 @@ def _convert_string_array(data: np.ndarray, encoding: str, errors: str) -> np.nd | |
# encode if needed | ||
if len(data): | ||
data = ( | ||
Series(data.ravel(), copy=False) | ||
Series(data.ravel(), copy=False, dtype="object") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We go immediately back to NumPy, so no reason to use string dtypes here. |
||
.str.encode(encoding, errors) | ||
._values.reshape(data.shape) | ||
) | ||
|
@@ -5264,7 +5318,9 @@ def _unconvert_string_array( | |
dtype = f"U{itemsize}" | ||
|
||
if isinstance(data[0], bytes): | ||
ser = Series(data, copy=False).str.decode(encoding, errors=errors) | ||
ser = Series(data, copy=False).str.decode( | ||
encoding, errors=errors, dtype="object" | ||
) | ||
Comment on lines
+5321
to
+5323
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We go immediately back to NumPy, so no reason to use string dtypes here. |
||
data = ser.to_numpy() | ||
data.flags.writeable = True | ||
else: | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This was added back in #54431. I do not believe it is no longer necessary - we will infer string in the Series constructor.