Skip to content

BUG: group with multiple named results #21171

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
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
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
23 changes: 22 additions & 1 deletion pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -2298,7 +2298,28 @@ def levels(self):

@property
def names(self):
return [ping.name for ping in self.groupings]
# add suffix to level name in case they contain duplicates (GH 19029):
Copy link
Contributor

Choose a reason for hiding this comment

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

this is super complicated, what exactly are you trying to do here?

Copy link
Author

Choose a reason for hiding this comment

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

Hi. The goal here is to add a suffix to duplicate entries:

# takes care of multiplicity:
['x', 'x', 'y', 'y']  => ['x_0', 'x_1', 'y_0', 'y_1']

Before the current version the code just enumerated all the entries regardless of their multiplicity:

['x', 'x', 'y', 'y']  => ['x_0', 'x_1', 'y_2', 'y_3']

For some reason I thought that the current version would be better suited.
I can switch back to the old (and probably less confusing) version if you want.

orig_names = [ping.name for ping in self.groupings]
# if no names were assigned return the original names
if all(x is None for x in orig_names):
return orig_names

suffixes = collections.defaultdict(int)
dups = {n: count for n, count in
collections.Counter(orig_names).items() if count > 1}
new_names = []
for name in orig_names:
if name not in dups:
new_names.append(name)
else:
if name is not None:
new_name = '{0}_{1}'.format(name, suffixes[name])
else:
new_name = '{0}'.format(suffixes[name])
suffixes[name] += 1
new_names.append(new_name)

return new_names

def size(self):
"""
Expand Down
4 changes: 0 additions & 4 deletions pandas/tests/groupby/test_categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,10 +558,6 @@ def test_as_index():
result = df.groupby(['cat', s], as_index=False, observed=True).sum()
tm.assert_frame_equal(result, expected)

# GH18872: conflicting names in desired index
with pytest.raises(ValueError):
df.groupby(['cat', s.rename('cat')], observed=True).sum()

# is original index dropped?
group_columns = ['cat', 'A']
expected = DataFrame(
Expand Down
41 changes: 41 additions & 0 deletions pandas/tests/groupby/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -1674,3 +1674,44 @@ def test_tuple_correct_keyerror():
[3, 4]]))
with tm.assert_raises_regex(KeyError, "(7, 8)"):
df.groupby((7, 8)).mean()


def test_dup_index_names():
# dup. index names in groupby operations should be renamed (GH 19029):
Copy link
Contributor

Choose a reason for hiding this comment

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

can you parameterize this

df = pd.DataFrame({'date': pd.date_range('5.1.2018', '5.3.2018'),
'vals': list(range(3))})

# duplicates get suffixed by integer position
mi = pd.MultiIndex.from_product([[5], [1, 2, 3]],
names=['date_0', 'date_1'])
expected = pd.Series(data=list(range(3)), index=mi, name='vals')
result = df.groupby([df.date.dt.month, df.date.dt.day])['vals'].sum()

tm.assert_series_equal(result, expected)

# 2 out of 3 are duplicates and None
mi = pd.MultiIndex.from_product([[2018], [5], [1, 2, 3]],
names=['0', '1', 'date'])
expected = pd.Series(data=list(range(3)), index=mi, name='vals')
result = df.groupby([df.date.dt.year.rename(None),
df.date.dt.month.rename(None),
df.date.dt.day])['vals'].sum()
tm.assert_series_equal(result, expected)

# 2 out of 3 names (not None) are duplicates, the remaining is None
mi = pd.MultiIndex.from_product([[2018], [5], [1, 2, 3]],
names=['date_0', None, 'date_1'])
expected = pd.Series(data=list(range(3)), index=mi, name='vals')
result = df.groupby([df.date.dt.year,
df.date.dt.month.rename(None),
df.date.dt.day])['vals'].sum()
tm.assert_series_equal(result, expected)

# all are None
mi = pd.MultiIndex.from_product([[2018], [5], [1, 2, 3]],
names=[None, None, None])
expected = pd.Series(data=list(range(3)), index=mi, name='vals')
result = df.groupby([df.date.dt.year.rename(None),
df.date.dt.month.rename(None),
df.date.dt.day.rename(None)])['vals'].sum()
tm.assert_series_equal(result, expected)
16 changes: 14 additions & 2 deletions pandas/tests/reshape/test_pivot.py
Original file line number Diff line number Diff line change
Expand Up @@ -1705,9 +1705,21 @@ def test_crosstab_with_numpy_size(self):
tm.assert_frame_equal(result, expected)

def test_crosstab_dup_index_names(self):
# GH 13279, GH 18872
# duplicated index name should get renamed (GH 19029)
s = pd.Series(range(3), name='foo')
pytest.raises(ValueError, pd.crosstab, s, s)
failed = False
try:
Copy link
Contributor

Choose a reason for hiding this comment

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

if you are asserting that this works, simply collect the result and compare vs expected

result = pd.crosstab(s, s)
except ValueError:
failed = True

assert failed is False

s0 = pd.Series(range(3), name='foo0')
s1 = pd.Series(range(3), name='foo1')
expected = pd.DataFrame(np.diag(np.ones(3, dtype='int64')),
index=s0, columns=s1)
tm.assert_frame_equal(result, expected)

@pytest.mark.parametrize("names", [['a', ('b', 'c')],
[('a', 'b'), 'c']])
Expand Down