-
-
Notifications
You must be signed in to change notification settings - Fork 18.4k
Accept CategoricalDtype in read_csv #17643
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
TomAugspurger
merged 19 commits into
pandas-dev:master
from
TomAugspurger:categorical-csv-2
Oct 2, 2017
Merged
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
e83a0b8
ENH: Accept CategoricalDtype in CSV reader
TomAugspurger 388e8a9
rework
TomAugspurger c5f6e04
Fixed basic implementation
TomAugspurger 4b588cd
Added casting
TomAugspurger e32d5be
Doc and cleanup
TomAugspurger 508dd1e
Fixed assignment of categoricals
TomAugspurger 6f175a7
Doc and test unexpected values
TomAugspurger 1545734
DOC: fixups
TomAugspurger de9e3ee
Merge remote-tracking branch 'upstream/master' into categorical-csv-2
TomAugspurger b80cff8
More coercion, use _recode_for_categories
TomAugspurger b028827
Refactor with maybe_convert_for_categorical
TomAugspurger fc34080
PEP8
TomAugspurger d100f0c
Type for 32bit
TomAugspurger 8600c50
REF: refactor to new method
TomAugspurger 8c4ab5b
Merge remote-tracking branch 'upstream/master' into categorical-csv-2
TomAugspurger 96d5144
py2 compat
TomAugspurger 3de75cd
Refactored
TomAugspurger f03798d
More in Categorical
TomAugspurger 9325a93
fixup! More in Categorical
TomAugspurger 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 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
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
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 |
---|---|---|
|
@@ -45,7 +45,7 @@ from pandas.core.dtypes.common import ( | |
is_bool_dtype, is_object_dtype, | ||
is_string_dtype, is_datetime64_dtype, | ||
pandas_dtype) | ||
from pandas.core.categorical import Categorical | ||
from pandas.core.categorical import Categorical, _recode_for_categories | ||
from pandas.core.algorithms import take_1d | ||
from pandas.core.dtypes.concat import union_categoricals | ||
from pandas import Index | ||
|
@@ -1267,19 +1267,14 @@ cdef class TextReader: | |
return self._string_convert(i, start, end, na_filter, | ||
na_hashset) | ||
elif is_categorical_dtype(dtype): | ||
# TODO: I suspect that _categorical_convert could be | ||
# optimized when dtype is an instance of CategoricalDtype | ||
codes, cats, na_count = _categorical_convert( | ||
self.parser, i, start, end, na_filter, | ||
na_hashset, self.c_encoding) | ||
# sort categories and recode if necessary | ||
cats = Index(cats) | ||
if not cats.is_monotonic_increasing: | ||
unsorted = cats.copy() | ||
cats = cats.sort_values() | ||
indexer = cats.get_indexer(unsorted) | ||
codes = take_1d(indexer, codes, fill_value=-1) | ||
|
||
return Categorical(codes, categories=cats, ordered=False, | ||
fastpath=True), na_count | ||
cat = Categorical._from_inferred_categories(cats, codes, dtype) | ||
return cat, na_count | ||
|
||
elif is_object_dtype(dtype): | ||
return self._string_convert(i, start, end, na_filter, | ||
na_hashset) | ||
|
@@ -2230,8 +2225,11 @@ def _concatenate_chunks(list chunks): | |
if common_type == np.object: | ||
warning_columns.append(str(name)) | ||
|
||
if is_categorical_dtype(dtypes.pop()): | ||
result[name] = union_categoricals(arrs, sort_categories=True) | ||
dtype = dtypes.pop() | ||
if is_categorical_dtype(dtype): | ||
sort_categories = isinstance(dtype, str) | ||
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. str -> string_types |
||
result[name] = union_categoricals(arrs, | ||
sort_categories=sort_categories) | ||
else: | ||
result[name] = np.concatenate(arrs) | ||
|
||
|
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 |
---|---|---|
|
@@ -21,6 +21,8 @@ | |
_ensure_platform_int, | ||
is_dtype_equal, | ||
is_datetimelike, | ||
is_datetime64_dtype, | ||
is_timedelta64_dtype, | ||
is_categorical, | ||
is_categorical_dtype, | ||
is_integer_dtype, | ||
|
@@ -509,6 +511,59 @@ def base(self): | |
""" compat, we are always our own object """ | ||
return None | ||
|
||
@classmethod | ||
def _from_inferred_categories(cls, inferred_categories, inferred_codes, | ||
dtype): | ||
"""Construct a Categorical from inferred values | ||
|
||
For inferred categories (`dtype` is None) the categories are sorted. | ||
For explicit `dtype`, the `inferred_categories` are cast to the | ||
appropriate type. | ||
|
||
Parameters | ||
---------- | ||
|
||
inferred_categories : Index | ||
inferred_codes : Index | ||
dtype : CategoricalDtype or 'category' | ||
|
||
Returns | ||
------- | ||
Categorical | ||
""" | ||
from pandas import Index, to_numeric, to_datetime, to_timedelta | ||
|
||
cats = Index(inferred_categories) | ||
|
||
known_categories = (isinstance(dtype, CategoricalDtype) and | ||
dtype.categories is not None) | ||
|
||
if known_categories: | ||
# Convert to a specialzed type with `dtype` if specified | ||
if dtype.categories.is_numeric(): | ||
cats = to_numeric(inferred_categories, errors='coerce') | ||
elif is_datetime64_dtype(dtype.categories): | ||
cats = to_datetime(inferred_categories, errors='coerce') | ||
elif is_timedelta64_dtype(dtype.categories): | ||
cats = to_timedelta(inferred_categories, errors='coerce') | ||
|
||
if known_categories: | ||
# recode from observation oder to dtype.categories order | ||
categories = dtype.categories | ||
codes = _recode_for_categories(inferred_codes, cats, categories) | ||
elif not cats.is_monotonic_increasing: | ||
# sort categories and recode for unknown categories | ||
unsorted = cats.copy() | ||
categories = cats.sort_values() | ||
codes = _recode_for_categories(inferred_codes, unsorted, | ||
categories) | ||
dtype = CategoricalDtype(categories, ordered=False) | ||
else: | ||
dtype = CategoricalDtype(cats, ordered=False) | ||
codes = inferred_codes | ||
|
||
return cls(codes, dtype=dtype, fastpath=True) | ||
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. much nicer |
||
|
||
@classmethod | ||
def from_array(cls, data, **kwargs): | ||
""" | ||
|
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
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
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.
maybe a separate sub-section for this