-
Notifications
You must be signed in to change notification settings - Fork 6.9k
[DataFrame] Implements mode, to_datetime, and get_dummies #1956
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 all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
92c1ac5
implement mode and fix getitem
kunalgosar 5c017f0
mode broken on misaligned partitions
kunalgosar d69d60b
fully implement mode
kunalgosar 61e16b3
implement to_datetime
kunalgosar 9c8f8a9
implement get_dummies
kunalgosar a621d8f
implement tests
kunalgosar 430360e
fix __getitem__
kunalgosar 40f66ea
fix python2 compatibility
kunalgosar 767dc8f
fix getitem bug
kunalgosar 7f89d9f
resolving comments
kunalgosar 102e27d
Adding documentation
kunalgosar bc2a443
resolving comment
kunalgosar 5a0b4b5
resolve name change
kunalgosar 928aed3
speeding up getitem
kunalgosar 44d0a0d
complete rebase
kunalgosar 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 |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| from __future__ import absolute_import | ||
| from __future__ import division | ||
| from __future__ import print_function | ||
|
|
||
| import pandas | ||
| import ray | ||
|
|
||
| from .dataframe import DataFrame | ||
| from .utils import _map_partitions | ||
|
|
||
|
|
||
| def to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, utc=None, | ||
| box=True, format=None, exact=True, unit=None, | ||
| infer_datetime_format=False, origin='unix'): | ||
| """Convert the arg to datetime format. If not Ray DataFrame, this falls | ||
| back on pandas. | ||
|
|
||
| Args: | ||
| errors ('raise' or 'ignore'): If 'ignore', errors are silenced. | ||
| dayfirst (bool): Date format is passed in as day first. | ||
| yearfirst (bool): Date format is passed in as year first. | ||
| utc (bool): retuns a UTC DatetimeIndex if True. | ||
| box (bool): If True, returns a DatetimeIndex. | ||
| format (string): strftime to parse time, eg "%d/%m/%Y". | ||
| exact (bool): If True, require an exact format match. | ||
| unit (string, default 'ns'): unit of the arg. | ||
| infer_datetime_format (bool): Whether or not to infer the format. | ||
| origin (string): Define the reference date. | ||
|
|
||
| Returns: | ||
| Type depends on input: | ||
|
|
||
| - list-like: DatetimeIndex | ||
| - Series: Series of datetime64 dtype | ||
| - scalar: Timestamp | ||
| """ | ||
| if not isinstance(arg, DataFrame): | ||
| return pandas.to_datetime(arg, errors=errors, dayfirst=dayfirst, | ||
| yearfirst=yearfirst, utc=utc, box=box, | ||
| format=format, exact=exact, unit=unit, | ||
| infer_datetime_format=infer_datetime_format, | ||
| origin=origin) | ||
| if errors == 'raise': | ||
| pandas.to_datetime(pandas.DataFrame(columns=arg.columns), | ||
| errors=errors, dayfirst=dayfirst, | ||
| yearfirst=yearfirst, utc=utc, box=box, | ||
| format=format, exact=exact, unit=unit, | ||
| infer_datetime_format=infer_datetime_format, | ||
| origin=origin) | ||
|
|
||
| def datetime_helper(df, cols): | ||
| df.columns = cols | ||
| return pandas.to_datetime(df, errors=errors, dayfirst=dayfirst, | ||
| yearfirst=yearfirst, utc=utc, box=box, | ||
| format=format, exact=exact, unit=unit, | ||
| infer_datetime_format=infer_datetime_format, | ||
| origin=origin) | ||
|
|
||
| datetime_series = _map_partitions(datetime_helper, arg._row_partitions, | ||
| arg.columns) | ||
| result = pandas.concat(ray.get(datetime_series), copy=False) | ||
| result.index = arg.index | ||
|
|
||
| return result |
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 |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| from __future__ import absolute_import | ||
| from __future__ import division | ||
| from __future__ import print_function | ||
|
|
||
| import ray | ||
| import pandas | ||
| import numpy as np | ||
|
|
||
| from pandas import compat | ||
| from pandas.core.dtypes.common import is_list_like | ||
| from itertools import cycle | ||
|
|
||
| from .dataframe import DataFrame | ||
| from .utils import _deploy_func | ||
|
|
||
|
|
||
| def get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False, | ||
| columns=None, sparse=False, drop_first=False): | ||
| """Convert categorical variable into indicator variables. | ||
|
|
||
| Args: | ||
| data (array-like, Series, or DataFrame): data to encode. | ||
| prefix (string, [string]): Prefix to apply to each encoded column | ||
| label. | ||
| prefix_sep (string, [string]): Separator between prefix and value. | ||
| dummy_na (bool): Add a column to indicate NaNs. | ||
| columns: Which columns to encode. | ||
| sparse (bool): Not Implemented: If True, returns SparseDataFrame. | ||
| drop_first (bool): Whether to remove the first level of encoded data. | ||
|
|
||
| Returns: | ||
| DataFrame or one-hot encoded data. | ||
| """ | ||
| if not isinstance(data, DataFrame): | ||
| return pandas.get_dummies(data, prefix=prefix, prefix_sep=prefix_sep, | ||
| dummy_na=dummy_na, columns=columns, | ||
| sparse=sparse, drop_first=drop_first) | ||
|
|
||
| if sparse: | ||
| raise NotImplementedError( | ||
| "SparseDataFrame is not implemented. " | ||
| "To contribute to Pandas on Ray, please visit " | ||
| "github.com/ray-project/ray.") | ||
|
|
||
| if columns is None: | ||
| columns_to_encode = data.dtypes.isin([np.dtype("O"), 'category']) | ||
| columns_to_encode = data.columns[columns_to_encode] | ||
| else: | ||
| columns_to_encode = columns | ||
|
|
||
| def check_len(item, name): | ||
| len_msg = ("Length of '{name}' ({len_item}) did not match the " | ||
| "length of the columns being encoded ({len_enc}).") | ||
|
|
||
| if is_list_like(item): | ||
| if not len(item) == len(columns_to_encode): | ||
| len_msg = len_msg.format(name=name, len_item=len(item), | ||
| len_enc=len(columns_to_encode)) | ||
| raise ValueError(len_msg) | ||
|
|
||
| check_len(prefix, 'prefix') | ||
| check_len(prefix_sep, 'prefix_sep') | ||
| if isinstance(prefix, compat.string_types): | ||
| prefix = cycle([prefix]) | ||
| prefix = [next(prefix) for i in range(len(columns_to_encode))] | ||
| if isinstance(prefix, dict): | ||
| prefix = [prefix[col] for col in columns_to_encode] | ||
|
|
||
| if prefix is None: | ||
| prefix = columns_to_encode | ||
|
|
||
| # validate separators | ||
| if isinstance(prefix_sep, compat.string_types): | ||
| prefix_sep = cycle([prefix_sep]) | ||
| prefix_sep = [next(prefix_sep) for i in range(len(columns_to_encode))] | ||
| elif isinstance(prefix_sep, dict): | ||
| prefix_sep = [prefix_sep[col] for col in columns_to_encode] | ||
|
|
||
| if set(columns_to_encode) == set(data.columns): | ||
| with_dummies = [] | ||
| dropped_columns = pandas.Index() | ||
| else: | ||
| with_dummies = data.drop(columns_to_encode, axis=1)._col_partitions | ||
| dropped_columns = data.columns.drop(columns_to_encode) | ||
|
|
||
| def get_dummies_remote(df, to_drop, prefix, prefix_sep): | ||
| df = df.drop(to_drop, axis=1) | ||
|
|
||
| if df.size == 0: | ||
| return df, df.columns | ||
|
|
||
| df = pandas.get_dummies(df, prefix=prefix, prefix_sep=prefix_sep, | ||
| dummy_na=dummy_na, columns=None, sparse=sparse, | ||
| drop_first=drop_first) | ||
| columns = df.columns | ||
| df.columns = pandas.RangeIndex(0, len(df.columns)) | ||
| return df, columns | ||
|
|
||
| total = 0 | ||
| columns = [] | ||
| for i, part in enumerate(data._col_partitions): | ||
| col_index = data._col_metadata.partition_series(i) | ||
|
|
||
| # TODO(kunalgosar): Handle the case of duplicate columns here | ||
| to_encode = col_index.index.isin(columns_to_encode) | ||
|
|
||
| to_encode = col_index[to_encode] | ||
| to_drop = col_index.drop(to_encode.index) | ||
|
|
||
| result = _deploy_func._submit( | ||
| args=(get_dummies_remote, part, to_drop, | ||
| prefix[total:total + len(to_encode)], | ||
| prefix_sep[total:total + len(to_encode)]), | ||
| num_return_vals=2) | ||
|
|
||
| with_dummies.append(result[0]) | ||
| columns.append(result[1]) | ||
| total += len(to_encode) | ||
|
|
||
| columns = ray.get(columns) | ||
| dropped_columns = dropped_columns.append(columns) | ||
|
|
||
| return DataFrame(col_partitions=with_dummies, | ||
| columns=dropped_columns, | ||
| index=data.index) | ||
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.
from futureThere 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.
resolved.