Skip to content

Defer Series.str.get_dummies to pandas.get_dummies #26686

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

Closed
Closed
Changes from all 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
26 changes: 12 additions & 14 deletions pandas/core/strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -999,23 +999,21 @@ def str_get_dummies(arr, sep='|'):
1 0 0 0
2 1 0 1
"""
arr = arr.fillna('')
try:
arr = sep + arr + sep
except TypeError:
arr = sep + arr.astype(str) + sep
from pandas.core.reshape.reshape import get_dummies
from pandas import Series

arr = arr.fillna('').astype('str')
Copy link
Contributor

Choose a reason for hiding this comment

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

Why is this astype needed?

Copy link
Author

Choose a reason for hiding this comment

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

astype is needed as otherwise Series.str.split fails when the datatype is not a string (e.g. NaN).

One of the example given in the docstring is:

>>> pd.Series(['a|b', np.nan, 'a|c']).str.get_dummies()
a  b  c
0  1  1  0
1  0  0  0
2  1  0  1


arr_split = arr.str.split(sep)

tags = set()
for ts in arr.str.split(sep):
tags.update(ts)
tags = sorted(tags - {""})
stacked = Series(np.concatenate(arr_split)) if len(arr) > 0 else Series()
stacked[stacked == ''] = np.nan
stacked_idx = np.repeat(np.arange(len(arr)), arr_split.str.len())

dummies = np.empty((len(arr), len(tags)), dtype=np.int64)
dummies_stacked = get_dummies(stacked)
dummies = dummies_stacked.groupby(by=stacked_idx).sum()

for i, t in enumerate(tags):
pat = sep + t + sep
dummies[:, i] = lib.map_infer(arr.values, lambda x: pat in x)
return dummies, tags
return dummies.values, dummies.columns.values


def str_join(arr, sep):
Expand Down