Skip to content

Commit 3d281cf

Browse files
committed
fixup for groupby
1 parent 0176228 commit 3d281cf

File tree

2 files changed

+66
-36
lines changed

2 files changed

+66
-36
lines changed

pandas/core/apply.py

+54-34
Original file line numberDiff line numberDiff line change
@@ -225,51 +225,66 @@ def agg_list_like(self, _axis: int) -> FrameOrSeriesUnion:
225225

226226
results = []
227227
keys = []
228+
ndims = []
228229

229230
# degenerate case
230-
if selected_obj.ndim == 1:
231-
for a in arg:
232-
colg = obj._gotitem(selected_obj.name, ndim=1, subset=selected_obj)
233-
try:
234-
new_res = colg.aggregate(a)
235-
236-
except TypeError:
237-
pass
231+
# if selected_obj.ndim == 1:
232+
for a in arg:
233+
# colg = obj._gotitem(selected_obj.name, ndim=1, subset=selected_obj)
234+
try:
235+
# new_res = colg.aggregate(a)
236+
print('selected_obj:', type(selected_obj))
237+
print(selected_obj)
238+
print('###')
239+
new_res = selected_obj.aggregate(a)
240+
print(new_res)
241+
242+
except TypeError:
243+
pass
244+
else:
245+
results.append(new_res)
246+
if isinstance(new_res, ABCNDFrame):
247+
ndims.append(new_res.ndim)
238248
else:
239-
results.append(new_res)
249+
ndims.append(0)
240250

241-
# make sure we find a good name
242-
name = com.get_callable_name(a) or a
243-
keys.append(name)
251+
# make sure we find a good name
252+
name = com.get_callable_name(a) or a
253+
keys.append(name)
244254

245255
# multiples
246-
else:
247-
for index, col in enumerate(selected_obj):
248-
colg = obj._gotitem(col, ndim=1, subset=selected_obj.iloc[:, index])
249-
try:
250-
new_res = colg.aggregate(arg)
251-
except (TypeError, DataError):
252-
pass
253-
except ValueError as err:
254-
# cannot aggregate
255-
if "Must produce aggregated value" in str(err):
256-
# raised directly in _aggregate_named
257-
pass
258-
elif "no results" in str(err):
259-
# raised directly in _aggregate_multiple_funcs
260-
pass
261-
else:
262-
raise
263-
else:
264-
results.append(new_res)
265-
keys.append(col)
256+
# else:
257+
# for index, col in enumerate(selected_obj):
258+
# colg = obj._gotitem(col, ndim=1, subset=selected_obj.iloc[:, index])
259+
# try:
260+
# new_res = colg.aggregate(arg)
261+
# except (TypeError, DataError):
262+
# pass
263+
# except ValueError as err:
264+
# # cannot aggregate
265+
# if "Must produce aggregated value" in str(err):
266+
# # raised directly in _aggregate_named
267+
# pass
268+
# elif "no results" in str(err):
269+
# # raised directly in _aggregate_multiple_funcs
270+
# pass
271+
# else:
272+
# raise
273+
# else:
274+
# results.append(new_res)
275+
# keys.append(col)
266276

267277
# if we are empty
268278
if not len(results):
269279
raise ValueError("no results")
270280

271281
try:
272-
return concat(results, keys=keys, axis=1, sort=False)
282+
# if len(results) == 0:
283+
# result = results[0]
284+
# else:
285+
result = concat(results, keys=keys, axis=1, sort=False)
286+
if all([e == 1 for e in ndims]):
287+
result = result.T.infer_objects()
273288
except TypeError as err:
274289

275290
# we are concatting non-NDFrame objects,
@@ -282,7 +297,12 @@ def agg_list_like(self, _axis: int) -> FrameOrSeriesUnion:
282297
raise ValueError(
283298
"cannot combine transform and aggregation operations"
284299
) from err
285-
return result
300+
else:
301+
if result.columns.nlevels > 1:
302+
new_order = [-1] + list(range(result.columns.nlevels - 1))
303+
result = result.reorder_levels(new_order, axis='columns')
304+
result = result[selected_obj.columns]
305+
return result
286306

287307
def agg_dict_like(self, _axis: int) -> FrameOrSeriesUnion:
288308
"""

pandas/tests/apply/test_frame_apply.py

+12-2
Original file line numberDiff line numberDiff line change
@@ -1101,6 +1101,7 @@ def test_consistency_for_boxed(self, box, int_frame_const_col):
11011101

11021102
class TestDataFrameAggregate:
11031103
def test_agg_transform(self, axis, float_frame):
1104+
float_frame = float_frame.head()
11041105
other_axis = 1 if axis in {0, "index"} else 0
11051106

11061107
with np.errstate(all="ignore"):
@@ -1124,11 +1125,16 @@ def test_agg_transform(self, axis, float_frame):
11241125
expected.index = pd.MultiIndex.from_product(
11251126
[float_frame.index, ["sqrt"]]
11261127
)
1128+
print("result")
1129+
print(result)
1130+
print('expected')
1131+
print(expected)
11271132
tm.assert_frame_equal(result, expected)
11281133

11291134
# multiple items in list
11301135
# these are in the order as if we are applying both
11311136
# functions per series and then concatting
1137+
print('marker')
11321138
result = float_frame.apply([np.abs, np.sqrt], axis=axis)
11331139
expected = zip_frames([f_abs, f_sqrt], axis=other_axis)
11341140
if axis in {0, "index"}:
@@ -1139,20 +1145,24 @@ def test_agg_transform(self, axis, float_frame):
11391145
expected.index = pd.MultiIndex.from_product(
11401146
[float_frame.index, ["absolute", "sqrt"]]
11411147
)
1148+
print()
1149+
print(result)
1150+
print()
1151+
print(expected)
11421152
tm.assert_frame_equal(result, expected)
11431153

11441154
def test_transform_and_agg_err(self, axis, float_frame):
11451155
# cannot both transform and agg
11461156
msg = "cannot combine transform and aggregation operations"
11471157
with pytest.raises(ValueError, match=msg):
11481158
with np.errstate(all="ignore"):
1149-
float_frame.agg(["max", "sqrt"], axis=axis)
1159+
print(float_frame.agg(["max", "sqrt"], axis=axis))
11501160

11511161
df = DataFrame({"A": range(5), "B": 5})
11521162

11531163
def f():
11541164
with np.errstate(all="ignore"):
1155-
df.agg({"A": ["abs", "sum"], "B": ["mean", "max"]}, axis=axis)
1165+
print(df.agg({"A": ["abs", "sum"], "B": ["mean", "max"]}, axis=axis))
11561166

11571167
def test_demo(self):
11581168
# demonstration tests

0 commit comments

Comments
 (0)