Skip to content

Commit 867a60a

Browse files
committed
cater for dataframes
1 parent ee251bc commit 867a60a

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

janitor/functions/summarize.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -172,8 +172,11 @@ def summarize(
172172
outcome = val.agg(funcn)
173173
except (ValueError, AttributeError):
174174
outcome = funcn(val)
175-
if is_scalar(outcome):
176-
outcome = [outcome]
177-
aggs[name] = outcome
178-
175+
if isinstance(outcome, pd.DataFrame):
176+
outcome.columns = f"{name}_" + outcome.columns
177+
aggs.update(outcome)
178+
else:
179+
if is_scalar(outcome):
180+
outcome = [outcome]
181+
aggs[name] = outcome
179182
return pd.DataFrame(aggs, copy=False)

tests/functions/test_summarize.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,3 +158,23 @@ def test_tuple_func_list_dupes(dataframe):
158158
(dataframe.dtypes.map(is_numeric_dtype), ["sum", np.sum, np.mean])
159159
).astype(float)
160160
assert_frame_equal(expected.sort_index(axis=1), actual.sort_index(axis=1))
161+
162+
163+
@pytest.mark.functions
164+
def test_tuple_dataframe(dataframe):
165+
"""Test output if a dataframe is returned"""
166+
df = [
167+
{"A": "foo", "B": "one", "C": -0.575247, "D": 1.346061},
168+
{"A": "bar", "B": "one", "C": 0.254161, "D": 1.511763},
169+
{"A": "foo", "B": "two", "C": -1.143704, "D": 1.627081},
170+
{"A": "bar", "B": "three", "C": 0.215897, "D": -0.990582},
171+
{"A": "foo", "B": "two", "C": 1.193555, "D": -0.441652},
172+
{"A": "bar", "B": "two", "C": -0.077118, "D": 1.211526},
173+
{"A": "foo", "B": "one", "C": -0.40853, "D": 0.26852},
174+
{"A": "foo", "B": "three", "C": -0.862495, "D": 0.02458},
175+
]
176+
177+
df = pd.DataFrame(df)
178+
expected = df.groupby("A").C.describe().add_prefix("C_")
179+
actual = df.summarize(("C", "describe"), by="A")
180+
assert_frame_equal(expected, actual)

0 commit comments

Comments
 (0)