-
- Notifications
You must be signed in to change notification settings - Fork 19.4k
Better error for str.cat with listlike of wrong dtype. #26607
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
Changes from 1 commit
Commits
Show all changes
9 commits Select commit Hold shift + click to select a range
cd9aa24 Better TypeError for wrong dtype in str.cat
h-vetinari fee9612 Merge remote-tracking branch 'upstream/master' into str_cat_err
h-vetinari fd710de Review (jreback)
h-vetinari e7f0d7e Merge remote-tracking branch 'upstream/master' into str_cat_err
h-vetinari bfca6d1 Merge remote-tracking branch 'upstream/master' into str_cat_err
h-vetinari 02f6429 Review (jreback & simonjayhawkins)
h-vetinari cb73704 Merge remote-tracking branch 'upstream/master' into str_cat_err
h-vetinari 3fb1411 Merge remote-tracking branch 'upstream/master' into str_cat_err
h-vetinari 9752aa7 Add typing to cat_core/cat_safe (review jreback)
h-vetinari 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
Review (jreback)
- Loading branch information
commit fd710dea08469b672b7e751d8ec0ceb3a4f2c060
There are no files selected for viewing
This file contains hidden or 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 |
|---|---|---|
| | @@ -53,6 +53,27 @@ def cat_core(list_of_columns, sep): | |
| return np.sum(list_with_sep, axis=0) | ||
| | ||
| | ||
| def cat_safe(list_of_columns, sep): | ||
| """ | ||
| Auxiliary function for :meth:`str.cat`. | ||
| | ||
| Same signature as cat_core, but handles TypeErrors in concatenation, which | ||
| happen if the Series in list_of columns have the wrong dtypes or content. | ||
| """ | ||
| # if there are any non-string values (wrong dtype or hidden behind object | ||
| ||
| # dtype), np.sum will fail; catch error and return with better message | ||
| try: | ||
| result = cat_core(list_of_columns, sep) | ||
| except TypeError: | ||
| dtypes = [lib.infer_dtype(x, skipna=True) for x in list_of_columns] | ||
| illegal = [x not in ('string', 'empty') for x in dtypes] | ||
| first_offender = [x for x, y in zip(list_of_columns, illegal) if y][0] | ||
simonjayhawkins marked this conversation as resolved. Outdated Show resolved Hide resolved | ||
| raise TypeError('Concatenation requires list-likes containing only ' | ||
| 'strings (or missing values). Offending values found ' | ||
| 'in column {}'.format(first_offender)) from None | ||
| return result | ||
| | ||
| | ||
| def _na_map(f, arr, na_result=np.nan, dtype=object): | ||
| # should really _check_ for NA | ||
| return _map(f, arr, na_mask=True, na_value=na_result, dtype=dtype) | ||
| | @@ -2280,23 +2301,6 @@ def cat(self, others=None, sep=None, na_rep=None, join=None): | |
| 'must all be of the same length as the ' | ||
| 'calling Series/Index.') | ||
| | ||
| # data has already been checked by _validate to be of correct dtype, | ||
| # but others could still have Series of dtypes (e.g. integers) which | ||
| # will necessarily fail in concatenation. To avoid deep and confusing | ||
| # traces, we raise here for anything that's not object or all-NA float. | ||
| def _legal_dtype(series): | ||
| # unify dtype handling between categorical/non-categorical | ||
| dtype = (series.dtype if not is_categorical_dtype(series) | ||
| else series.cat.categories.dtype) | ||
| legal = dtype == 'O' or (dtype == 'float' and series.isna().all()) | ||
| return legal | ||
| err_wrong_dtype = ('Can only concatenate list-likes containing only ' | ||
| 'strings (or missing values).') | ||
| if any(not _legal_dtype(x) for x in others): | ||
| raise TypeError(err_wrong_dtype + ' Received list-like of dtype: ' | ||
| '{}'.format([x.dtype for x in others | ||
| if not _legal_dtype(x)][0])) | ||
| | ||
| if join is None and warn: | ||
| warnings.warn("A future version of pandas will perform index " | ||
| "alignment when `others` is a Series/Index/" | ||
| | @@ -2324,28 +2328,23 @@ def _legal_dtype(series): | |
| na_masks = np.array([isna(x) for x in all_cols]) | ||
| union_mask = np.logical_or.reduce(na_masks, axis=0) | ||
| | ||
| # if there are any non-string, non-null values hidden within an object | ||
| # dtype, cat_core will fail; catch error and return with better message | ||
| try: | ||
| if na_rep is None and union_mask.any(): | ||
| # no na_rep means NaNs for all rows where any column has a NaN | ||
| # only necessary if there are actually any NaNs | ||
| result = np.empty(len(data), dtype=object) | ||
| np.putmask(result, union_mask, np.nan) | ||
| | ||
| not_masked = ~union_mask | ||
| result[not_masked] = cat_core([x[not_masked] | ||
| for x in all_cols], sep) | ||
| elif na_rep is not None and union_mask.any(): | ||
| # fill NaNs with na_rep in case there are actually any NaNs | ||
| all_cols = [np.where(nm, na_rep, col) | ||
| for nm, col in zip(na_masks, all_cols)] | ||
| result = cat_core(all_cols, sep) | ||
| else: | ||
| # no NaNs - can just concatenate | ||
| result = cat_core(all_cols, sep) | ||
| except TypeError: | ||
| raise TypeError(err_wrong_dtype) | ||
| if na_rep is None and union_mask.any(): | ||
| # no na_rep means NaNs for all rows where any column has a NaN | ||
| # only necessary if there are actually any NaNs | ||
| result = np.empty(len(data), dtype=object) | ||
| np.putmask(result, union_mask, np.nan) | ||
| | ||
| not_masked = ~union_mask | ||
| result[not_masked] = cat_safe([x[not_masked] for x in all_cols], | ||
| sep) | ||
| elif na_rep is not None and union_mask.any(): | ||
| # fill NaNs with na_rep in case there are actually any NaNs | ||
| all_cols = [np.where(nm, na_rep, col) | ||
| for nm, col in zip(na_masks, all_cols)] | ||
| result = cat_safe(all_cols, sep) | ||
| else: | ||
| # no NaNs - can just concatenate | ||
| result = cat_safe(all_cols, sep) | ||
| | ||
| if isinstance(self._orig, Index): | ||
| # add dtype for case that result is all-NA | ||
| | ||
This file contains hidden or 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
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.
can you type the args & return value & add a Parameters / Returns section
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.
What's your expectation for typing the args? Just
List? It would strictly speaking beList[np.array], but AFAICT, mypy resp. the typing module doesn't yet support numpy stubs natively.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.
yes that would be fine