costream 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
costream/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,9 @@
1
+ from .loader import group_files_by_subject, make_csv_loader
2
+ from .utils import get_event_starts, extract_streaming_data
3
+
4
+ __all__ = [
5
+ "group_files_by_subject",
6
+ "make_csv_loader",
7
+ "get_event_starts",
8
+ "extract_streaming_data"
9
+ ]
@@ -0,0 +1,131 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from collections import defaultdict
5
+ from pathlib import Path
6
+ from typing import Callable, Dict, List, Optional, Sequence, Union
7
+
8
+ import pandas as pd
9
+ import numpy as np
10
+
11
+ __all__ = ["group_files_by_subject", "make_csv_loader"]
12
+
13
+ def group_files_by_subject(
14
+ data_dir: Union[str, Path],
15
+ id_extractor: Optional[Callable[[str], str]] = None,
16
+ file_pattern: str = "*.csv"
17
+ ) -> Dict[str, List[Path]]:
18
+ """
19
+ Group files in a directory into a mapping of {subject_id: [file_paths]}.
20
+ """
21
+ base_dir = Path(data_dir)
22
+ if not base_dir.is_dir():
23
+ raise FileNotFoundError(f"Directory not found: {base_dir}")
24
+
25
+ if id_extractor is None:
26
+ def _default_extractor(p: Path) -> str:
27
+ name = p.stem
28
+ m = re.match(r"^([^_-]+)", name)
29
+ return m.group(1) if m else name
30
+ id_extractor = _default_extractor
31
+
32
+ mapping = defaultdict(list)
33
+ files = list(base_dir.glob(file_pattern))
34
+
35
+ if not files:
36
+ # Try recursive if flat search fails
37
+ files = list(base_dir.rglob(file_pattern))
38
+
39
+ for path in files:
40
+ sid = id_extractor(path)
41
+ mapping[sid].append(path)
42
+
43
+ for sid in mapping:
44
+ mapping[sid].sort()
45
+
46
+ return dict(mapping)
47
+
48
+
49
+ def make_csv_loader(
50
+ feature_cols: Optional[Sequence[str]] = None,
51
+ label_col: str = "label",
52
+ timestamp_col: Optional[str] = None,
53
+ parse_dates: bool = False,
54
+ new_features: Optional[Dict[str, Callable[[pd.DataFrame], pd.Series]]] = None,
55
+ label_extractor: Optional[Callable[[pd.DataFrame, Path], pd.DataFrame]] = None,
56
+ **read_csv_kwargs
57
+ ) -> Callable[[Sequence[Union[str, Path]]], List[pd.DataFrame]]:
58
+ """
59
+ Creates a factory function to load CSV files into standardized DataFrames.
60
+
61
+ Args:
62
+ feature_cols: List of columns to keep as input features.
63
+ label_col: Name of the target column (0=normal, 1=event).
64
+ timestamp_col: Optional name of the timestamp column.
65
+ parse_dates: If True, parses the timestamp column as datetime.
66
+ new_features: Dictionary of {new_col_name: function(df) -> series}.
67
+ label_extractor: Optional function(df, path) -> df.
68
+ Used to inject labels based on filename/path (e.g. for SisFall).
69
+ Must ensure the dataframe has a column named `label_col` after execution.
70
+ **read_csv_kwargs: Arguments for pd.read_csv (e.g. header=None, names=['x','y','z']).
71
+
72
+ Returns:
73
+ A function `load_signals(files)` that returns a list of DataFrames.
74
+ """
75
+
76
+ def load_signals(files: Sequence[Union[str, Path]]) -> List[pd.DataFrame]:
77
+ dfs: List[pd.DataFrame] = []
78
+
79
+ for f in files:
80
+ path = Path(f)
81
+ if not path.exists():
82
+ raise FileNotFoundError(f"File not found: {path}")
83
+
84
+ # Prepare date parsing args
85
+ parse_arg = read_csv_kwargs.pop('parse_dates', None)
86
+ if parse_dates and timestamp_col:
87
+ parse_arg = [timestamp_col]
88
+
89
+ # Load Raw
90
+ df = pd.read_csv(path, parse_dates=parse_arg, **read_csv_kwargs)
91
+
92
+ # Generate derived features (e.g., Magnitude)
93
+ if new_features:
94
+ for new_col_name, func in new_features.items():
95
+ df[new_col_name] = func(df)
96
+
97
+ # Inject Labels (for simulated datasets without label columns)
98
+ if label_extractor:
99
+ df = label_extractor(df, path)
100
+
101
+ # Check label column existence
102
+ if label_col not in df.columns:
103
+ raise ValueError(
104
+ f"Label column '{label_col}' not found in {path.name}. "
105
+ f"If the file has no label column, provide a `label_extractor`."
106
+ )
107
+
108
+ # 3. Determine which columns to keep
109
+ if feature_cols is None:
110
+ exclude = {c for c in (timestamp_col, label_col) if c}
111
+ selected_features = [c for c in df.columns if c not in exclude]
112
+ else:
113
+ selected_features = list(feature_cols)
114
+ missing = [c for c in selected_features if c not in df.columns]
115
+ if missing:
116
+ raise KeyError(f"Missing feature columns in {path.name}: {missing}")
117
+
118
+ # 4. Filter and Type Cast
119
+ cols_to_keep = selected_features + [label_col]
120
+ if timestamp_col and timestamp_col in df.columns:
121
+ cols_to_keep.append(timestamp_col)
122
+
123
+ df = df[cols_to_keep].copy()
124
+ df[selected_features] = df[selected_features].astype("float32")
125
+ df[label_col] = df[label_col].astype("int8")
126
+
127
+ dfs.append(df)
128
+
129
+ return dfs
130
+
131
+ return load_signals
costream/data/utils.py ADDED
@@ -0,0 +1,91 @@
1
+ """
2
+ Data utility functions for processing signals and labels.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import Dict, List, Sequence, Tuple, Union, Optional
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+ __all__ = ["get_event_starts", "extract_streaming_data"]
13
+
14
+
15
+ def get_event_starts(labels: np.ndarray) -> Union[int, np.ndarray]:
16
+ """
17
+ Identify the start indices of distinct events from a label array.
18
+
19
+ Handles contiguous blocks of non-zero labels.
20
+ Example: [0, 0, 1, 1, 1, 0, 2, 2] -> Returns [2, 6]
21
+
22
+ Parameters
23
+ ----------
24
+ labels : np.ndarray
25
+ Array of integer labels (0=Background, >0=Event).
26
+
27
+ Returns
28
+ -------
29
+ int or np.ndarray
30
+ -1 if no events found.
31
+ Array of start indices if events exist.
32
+ """
33
+ labels = np.asarray(labels)
34
+ non_zero_indices = np.flatnonzero(labels)
35
+
36
+ if non_zero_indices.size == 0:
37
+ return -1
38
+
39
+ # Find gaps > 1 sample to identify distinct event blocks
40
+ gaps = np.diff(non_zero_indices) > 1
41
+
42
+ # The starts are: the very first non-zero index...
43
+ # ...PLUS the indices immediately following any gap.
44
+ starts = np.insert(non_zero_indices[1:][gaps], 0, non_zero_indices[0])
45
+
46
+ return starts
47
+
48
+
49
+ def extract_streaming_data(
50
+ subject_map: Dict[str, List[pd.DataFrame]],
51
+ subjects: Sequence[str],
52
+ feature_col: str,
53
+ label_col: str = "label"
54
+ ) -> Tuple[List[np.ndarray], List[Union[int, np.ndarray]]]:
55
+ """
56
+ Extract raw signals and robust event start indices for a list of subjects.
57
+
58
+ Parameters
59
+ ----------
60
+ subject_map : dict
61
+ Dictionary {subject_id: [DataFrame, ...]}.
62
+ subjects : list
63
+ List of subject IDs to process.
64
+ feature_col : str
65
+ Name of the column containing the signal (e.g., 'mag').
66
+ label_col : str
67
+ Name of the label column.
68
+
69
+ Returns
70
+ -------
71
+ signals : List[np.ndarray]
72
+ List of 1D float arrays (the streams).
73
+ events : List[Union[int, np.ndarray]]
74
+ List of event start indices (or -1) corresponding to each stream.
75
+ """
76
+ signals = []
77
+ events = []
78
+
79
+ for s in subjects:
80
+ if s in subject_map:
81
+ for df in subject_map[s]:
82
+ # 1. Extract Signal
83
+ sig = df[feature_col].to_numpy(dtype=np.float32)
84
+ signals.append(sig)
85
+
86
+ # 2. Extract Event Starts
87
+ labels = df[label_col].to_numpy()
88
+ starts = get_event_starts(labels)
89
+ events.append(starts)
90
+
91
+ return signals, events
@@ -0,0 +1,39 @@
1
+ from .tester import run_experiment, ModelSpec, train_models, evaluate_models
2
+ from .event_detection import evaluate_recording, FalsePositive
3
+ from .presegmented import evaluate_presegmented
4
+ from .cross_validation import run_subject_cv, aggregate_cv_results
5
+ from .probability_cache import CacheKey, CachedEntry, ProbabilityCache
6
+ from .checks import assert_adl_exclusion_zone, assert_gate_applied_identically
7
+ from .visualization import (
8
+ plot_confidence,
9
+ plot_detection,
10
+ metric_box,
11
+ metric_grid,
12
+ plot_grouped_stacked,
13
+ critical_difference,
14
+ window_bar,
15
+ )
16
+
17
+ __all__ = [
18
+ "run_experiment",
19
+ "ModelSpec",
20
+ "train_models",
21
+ "evaluate_models",
22
+ "evaluate_recording",
23
+ "FalsePositive",
24
+ "evaluate_presegmented",
25
+ "assert_adl_exclusion_zone",
26
+ "assert_gate_applied_identically",
27
+ "run_subject_cv",
28
+ "aggregate_cv_results",
29
+ "CacheKey",
30
+ "CachedEntry",
31
+ "ProbabilityCache",
32
+ "plot_confidence",
33
+ "plot_detection",
34
+ "metric_box",
35
+ "metric_grid",
36
+ "plot_grouped_stacked",
37
+ "critical_difference",
38
+ "window_bar",
39
+ ]
@@ -0,0 +1,107 @@
1
+ """
2
+ Standalone sanity checks for the cross-protocol experiment.
3
+
4
+ These are auditors, not instrumentation — they drive the real segmentation functions
5
+ and check their actual output, rather than reimplementing the logic under test.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Iterable, List, Sequence
11
+
12
+ import numpy as np
13
+ import pandas as pd
14
+
15
+ from ..segmentation.training_segmenter import create_training_data
16
+ from ..segmentation.streaming_segmenter import generate_sliding_windows
17
+
18
+ __all__ = ["assert_adl_exclusion_zone", "assert_gate_applied_identically"]
19
+
20
+
21
+ def assert_adl_exclusion_zone(
22
+ dfs: Iterable[pd.DataFrame],
23
+ feature_col: str,
24
+ label_col: str,
25
+ *,
26
+ window_size: float,
27
+ step: float = 1.0,
28
+ freq: int = 100,
29
+ tolerance: float = 20.0,
30
+ spacing="multiphase",
31
+ ) -> None:
32
+ """Assert no ADL window `create_training_data` actually retains starts in
33
+ `[f - (w + tolerance), f + tolerance)` for any fall `f` in its own recording.
34
+
35
+ This is a real black-box test of `create_training_data`, not a reimplementation
36
+ of it: `create_training_data`'s (X, y) return loses each window's source
37
+ recording/start index, so this rebuilds a same-shape/same-fall-index copy of each
38
+ input recording whose *signal value at every sample equals that sample's own
39
+ index* (with the gate disabled via `signal_thresh=0`, isolating the exclusion-zone
40
+ effect from the activity gate). A kept ADL window's first sample then reveals
41
+ exactly which start index `create_training_data` retained it from.
42
+ """
43
+ encoded_dfs = []
44
+ fall_indices_per_df = []
45
+ for df in dfs:
46
+ n = len(df)
47
+ labels = df[label_col].to_numpy()
48
+ nonzero = np.flatnonzero(labels)
49
+ if nonzero.size == 0:
50
+ continue
51
+ gaps = np.diff(nonzero) > 1
52
+ event_starts = np.insert(nonzero[1:][gaps], 0, nonzero[0])
53
+ encoded_dfs.append(pd.DataFrame({feature_col: np.arange(n, dtype=np.float32), label_col: labels}))
54
+ fall_indices_per_df.append(event_starts)
55
+
56
+ violations = []
57
+ for df, falls in zip(encoded_dfs, fall_indices_per_df):
58
+ X, y = create_training_data(
59
+ [df], feature_cols=[feature_col], label_col=label_col,
60
+ window_size=window_size, step=step, freq=freq,
61
+ signal_thresh=0.0, drop_below_threshold=True, spacing=spacing,
62
+ )
63
+ adl_starts = X[y == 0][:, 0].astype(int) # first sample = encoded start index
64
+ for f in falls:
65
+ lo, hi = f - (window_size + tolerance) * freq, f + tolerance * freq
66
+ bad = adl_starts[(adl_starts >= lo) & (adl_starts < hi)]
67
+ violations.extend((int(f), int(w)) for w in bad)
68
+
69
+ assert not violations, (
70
+ f"{len(violations)} ADL window(s) create_training_data actually retained start "
71
+ f"inside the exclusion zone [f-(w+{tolerance}), f+{tolerance}) for their "
72
+ f"recording's fall — (fall_index, window_start) sample: {violations[:10]}"
73
+ )
74
+
75
+
76
+ def assert_gate_applied_identically(
77
+ *,
78
+ window_size: float = 5.0,
79
+ step: float = 1.0,
80
+ freq: int = 100,
81
+ threshold: float = 1.4,
82
+ ts_len: int = 20_000,
83
+ rng_seed: int = 0,
84
+ ) -> None:
85
+
86
+ rng = np.random.default_rng(rng_seed)
87
+ ts = rng.uniform(0.5, 2.5, size=ts_len).astype(np.float32)
88
+ labels = np.zeros(ts_len, dtype=np.int64) # no events: every window is a candidate
89
+
90
+ _, _, valid_mask, _ = generate_sliding_windows(
91
+ ts, window_size=window_size, step=step, freq=freq, signal_thresh=threshold
92
+ )
93
+ n_streaming_admitted = int(valid_mask.sum())
94
+
95
+ df = pd.DataFrame({"mag": ts, "label": labels})
96
+ X, y = create_training_data(
97
+ [df], feature_cols=["mag"], label_col="label",
98
+ window_size=window_size, step=step, freq=freq,
99
+ signal_thresh=threshold, drop_below_threshold=True,
100
+ )
101
+ n_training_admitted = int((y == 0).sum())
102
+
103
+ assert n_streaming_admitted == n_training_admitted, (
104
+ f"Gate admitted {n_streaming_admitted} windows via generate_sliding_windows "
105
+ f"but {n_training_admitted} via create_training_data for the same signal, "
106
+ f"window_size, step, freq, and threshold — the two gate paths have diverged."
107
+ )
@@ -0,0 +1,241 @@
1
+ """
2
+ Subject-wise Cross-Validation utilities.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from pathlib import Path
8
+ import numpy as np
9
+ import pandas as pd
10
+ from typing import List, Sequence, Dict, Optional, Union
11
+ from sklearn.model_selection import GroupKFold
12
+
13
+ # Internal package imports
14
+ from ..segmentation.training_segmenter import create_training_data
15
+ from ..data.utils import extract_streaming_data
16
+ from .tester import ModelSpec, train_models, evaluate_models
17
+ from .presegmented import evaluate_presegmented
18
+ from .probability_cache import ProbabilityCache
19
+
20
+ __all__ = ["run_subject_cv", "aggregate_cv_results"]
21
+
22
+
23
+ def run_subject_cv(
24
+ subject_map: Dict[str, List[pd.DataFrame]],
25
+ model_specs: List[ModelSpec],
26
+ feature_cols: Sequence[str],
27
+ label_col: str = "label",
28
+ cv: int = 5,
29
+ random_state: int = 42,
30
+ # Segmentation Params
31
+ window_size: float = 7.0,
32
+ step: float = 1.0,
33
+ freq: int = 100,
34
+ activity_threshold: float = 1.4,
35
+ drop_below_threshold: bool = True,
36
+ spacing: Union[int, str] = 5,
37
+ exclusion_tolerance: float = 20.0,
38
+ use_post_event_data: bool = True,
39
+ # Streaming/Eval Params
40
+ tolerance: float = 20.0,
41
+ debounce_secs: float = 60.0,
42
+ verbose: bool = True,
43
+
44
+ cache_dir: Optional[Union[str, Path]] = None,
45
+
46
+ resample: bool = True,
47
+ ) -> pd.DataFrame:
48
+ """
49
+ Orchestrate a Subject-Wise Cross-Validation experiment.
50
+
51
+ 1. Splits subjects into K folds.
52
+ 2. For each fold:
53
+ - Segments the training subjects into (X_train, y_train) and fits every
54
+ model spec on it ONCE.
55
+ - Evaluates those same frozen model instances under BOTH protocols:
56
+ Protocol A (presegmented, `evaluate_presegmented` — builds the test
57
+ fold's window set via the identical `create_training_data` call used
58
+ for training) and Protocol B (streaming, `evaluate_models`).
59
+ 3. Aggregates results into a single DataFrame with `fold` and `protocol`
60
+ columns ("A" or "B").
61
+
62
+ Parameters
63
+ ----------
64
+ subject_map : dict
65
+ Mapping of {subject_id: [list of dataframes]}.
66
+ (Usually output of costream.data.loader.load_subject with grouping).
67
+ model_specs : list[ModelSpec]
68
+ Models to evaluate.
69
+ feature_cols : list[str]
70
+ Columns to use as features.
71
+ label_col : str
72
+ Name of label column.
73
+ cv : int
74
+ Number of folds.
75
+
76
+ Returns
77
+ -------
78
+ pd.DataFrame
79
+ Combined results suitable for statistical analysis.
80
+ """
81
+
82
+ subjects = np.array(list(subject_map.keys()))
83
+
84
+ # Handle case where fewer subjects than folds
85
+ if len(subjects) < cv:
86
+ raise ValueError(
87
+ f"Cannot perform {cv}-fold CV with only {len(subjects)} subjects."
88
+ )
89
+
90
+ gkf = GroupKFold(n_splits=cv)
91
+
92
+ # We use subjects as both X and groups for the splitter
93
+ # (The actual data isn't split here, just the IDs)
94
+ split_gen = gkf.split(subjects, groups=subjects)
95
+
96
+ cache = ProbabilityCache(cache_dir) if cache_dir is not None else None
97
+
98
+ all_results = []
99
+ all_false_positives = []
100
+
101
+ for fold_idx, (train_idx, test_idx) in enumerate(split_gen, start=1):
102
+ train_subjs = subjects[train_idx]
103
+ test_subjs = subjects[test_idx]
104
+
105
+ if verbose:
106
+ print(
107
+ f"\n=== Fold {fold_idx}/{cv} | Train Subjects: {len(train_subjs)} | Test Subjects: {len(test_subjs)} ==="
108
+ )
109
+
110
+ # 1. Prepare Training Data (Segmented)
111
+ # Collect all DFs for training subjects
112
+ train_dfs = []
113
+ for s in train_subjs:
114
+ train_dfs.extend(subject_map[s])
115
+
116
+ X_train, y_train = create_training_data(
117
+ train_dfs,
118
+ feature_cols=feature_cols,
119
+ label_col=label_col,
120
+ window_size=window_size,
121
+ step=step,
122
+ freq=freq,
123
+ signal_thresh=activity_threshold,
124
+ drop_below_threshold=drop_below_threshold,
125
+ spacing=spacing,
126
+ exclusion_tolerance=exclusion_tolerance,
127
+ use_post_event_data=use_post_event_data,
128
+ )
129
+
130
+ if verbose:
131
+ print(f" Segmented Train Data: {X_train.shape}")
132
+
133
+ # Fit every model spec ONCE on this fold's training data. Both protocols
134
+ # below evaluate these exact same fitted instances.
135
+ trained_models = train_models(
136
+ X_train, y_train, model_specs, verbose=verbose, random_state=random_state,
137
+ resample=resample,
138
+ )
139
+
140
+ # 2a. Protocol B — streaming, over the test subjects' continuous signals
141
+ test_signals, test_events = extract_streaming_data(
142
+ subject_map=subject_map,
143
+ subjects=test_subjs,
144
+ feature_col=feature_cols[0],
145
+ label_col=label_col,
146
+ )
147
+
148
+ # Signal ids for the probability cache, matching extract_streaming_data's
149
+ # own iteration order (subject, then that subject's recordings in order) so
150
+ # they line up 1:1 with test_signals/test_events without changing that
151
+ # function's public contract.
152
+ signal_ids = [
153
+ f"{s}_{i}"
154
+ for s in test_subjs if s in subject_map
155
+ for i in range(len(subject_map[s]))
156
+ ]
157
+
158
+ streaming_results = evaluate_models(
159
+ trained_models,
160
+ test_signals,
161
+ test_events,
162
+ window_size=window_size,
163
+ step=step,
164
+ freq=freq,
165
+ signal_thresh=activity_threshold,
166
+ tolerance=tolerance,
167
+ debounce_secs=debounce_secs,
168
+ verbose=False,
169
+ cache=cache,
170
+ fold=fold_idx,
171
+ seed=random_state,
172
+ signal_ids=signal_ids,
173
+ )
174
+ streaming_results["protocol"] = "B"
175
+
176
+ # pd.concat below isn't guaranteed to preserve .attrs, so pull this fold's
177
+ # false-positive records out now and accumulate them separately (change
178
+ # request item 4).
179
+ fold_fps = streaming_results.attrs.get("false_positives")
180
+ if fold_fps is not None and len(fold_fps):
181
+ fold_fps = fold_fps.copy()
182
+ fold_fps["fold"] = fold_idx
183
+ all_false_positives.append(fold_fps)
184
+
185
+ # 2b. Protocol A — presegmented, over the SAME test subjects' dataframes,
186
+ # windowed by the SAME create_training_data call used for training.
187
+ test_dfs = [df for s in test_subjs if s in subject_map for df in subject_map[s]]
188
+ presegmented_results = evaluate_presegmented(
189
+ trained_models,
190
+ test_dfs,
191
+ feature_cols=feature_cols,
192
+ label_col=label_col,
193
+ window_size=window_size,
194
+ step=step,
195
+ freq=freq,
196
+ signal_thresh=activity_threshold,
197
+ drop_below_threshold=drop_below_threshold,
198
+ spacing=spacing,
199
+ exclusion_tolerance=exclusion_tolerance,
200
+ use_post_event_data=use_post_event_data,
201
+ verbose=verbose,
202
+ )
203
+ presegmented_results["protocol"] = "A"
204
+
205
+ # 3. Combine both protocols for this fold
206
+ fold_results = pd.concat([streaming_results, presegmented_results], ignore_index=True)
207
+ fold_results["fold"] = fold_idx
208
+ all_results.append(fold_results)
209
+
210
+ # if verbose:
211
+ # # Print quick summary of this fold
212
+ # print(" Fold Results (Mean F1):")
213
+ # print(fold_results.groupby("model")["f1-score"].mean())
214
+
215
+ # 4. Aggregate
216
+ final_df = pd.concat(all_results, ignore_index=True)
217
+ final_df.attrs["false_positives"] = (
218
+ pd.concat(all_false_positives, ignore_index=True) if all_false_positives
219
+ else pd.DataFrame(columns=["model", "signal_id", "alarm_idx", "nearest_event", "offset_seconds", "fold"])
220
+ )
221
+ return final_df
222
+
223
+ def aggregate_cv_results(df: pd.DataFrame, group: Union[str, List[str], None] = None,
224
+ exclude_cols: list = []) -> pd.DataFrame:
225
+ """Return mean ± std for each metric.
226
+ """
227
+ if group is None:
228
+ group = ["model", "protocol"] if "protocol" in df.columns else "model"
229
+ if exclude_cols==[]:
230
+ exclude_cols = ["seed", "fold"]
231
+ else:
232
+ exclude_cols = exclude_cols + ["seed", "fold"]
233
+ num_cols = [c for c in df.select_dtypes(include=[np.number]).columns
234
+ if c not in exclude_cols]
235
+ means = df.groupby(group)[num_cols].mean()
236
+ stds = df.groupby(group)[num_cols].std()
237
+ aggr = pd.DataFrame(index=means.index)
238
+ for col in num_cols:
239
+ aggr[col] = means[col].round(2).astype(str) + " ± " + stds[col].round(2).astype(str)
240
+ aggr.reset_index(inplace=True)
241
+ return aggr