#!/usr/bin/env python3 """Поиск выбросов в числовых колонках CSV.""" from __future__ import annotations import argparse from pathlib import Path import pandas as pd def main() -> int: parser = argparse.ArgumentParser(description="Найти выбросы в CSV") parser.add_argument("--input", type=Path, required=True, help="Исходный CSV") parser.add_argument("--report", type=Path, default=Path("outliers.csv"), help="Отчёт о выбросах") parser.add_argument("--clean-output", type=Path, help="Куда сохранить строки без выбросов") parser.add_argument("--columns", default="", help="Числовые колонки через запятую") parser.add_argument("--method", choices=["iqr", "zscore"], default="iqr", help="Метод поиска") parser.add_argument("--threshold", type=float, default=1.5, help="Множитель IQR или порог z-score") parser.add_argument("--force", action="store_true", help="Перезаписать выходные файлы") args = parser.parse_args() source = args.input.expanduser().resolve() report = args.report.expanduser().resolve() if not source.is_file(): parser.error(f"Файл не найден: {source}") if source == report: parser.error("Отчёт не должен совпадать с исходным файлом") if report.exists() and not args.force: parser.error(f"Файл уже существует: {report}. Добавьте --force") if args.clean_output and args.clean_output.expanduser().resolve() in {source, report}: parser.error("Очищенный файл не должен совпадать с исходным или отчётом") if args.clean_output and args.clean_output.expanduser().resolve().exists() and not args.force: parser.error(f"Файл уже существует: {args.clean_output}. Добавьте --force") frame = pd.read_csv(source, encoding="utf-8-sig") columns = [item.strip() for item in args.columns.split(",") if item.strip()] if not columns: columns = list(frame.select_dtypes(include="number").columns) if not columns: parser.error("Не найдено числовых колонок, укажите их через --columns") flagged_rows: set[int] = set() records: list[dict[str, object]] = [] for column in columns: if column not in frame.columns: parser.error(f"Нет колонки: {column}") series = pd.to_numeric(frame[column], errors="coerce") if args.method == "iqr": q1 = series.quantile(0.25) q3 = series.quantile(0.75) spread = q3 - q1 low = q1 - args.threshold * spread high = q3 + args.threshold * spread mask = (series < low) | (series > high) else: mean = series.mean() std = series.std(ddof=0) if std == 0 or pd.isna(std): low = mean high = mean mask = pd.Series(False, index=series.index) else: low = mean - args.threshold * std high = mean + args.threshold * std mask = ((series - mean) / std).abs() > args.threshold for index in series[mask].index: flagged_rows.add(int(index)) records.append({ "row": int(index) + 1, "column": column, "value": series.loc[index], "lower": round(float(low), 4), "upper": round(float(high), 4), "method": args.method, }) print(f"{column}: выбросов {int(mask.sum())}") report_frame = pd.DataFrame(records, columns=["row", "column", "value", "lower", "upper", "method"]) report.parent.mkdir(parents=True, exist_ok=True) report_frame.to_csv(report, index=False, encoding="utf-8-sig") if args.clean_output: clean = frame.drop(index=sorted(flagged_rows)) clean_path = args.clean_output.expanduser().resolve() clean_path.parent.mkdir(parents=True, exist_ok=True) clean.to_csv(clean_path, index=False, encoding="utf-8-sig") print(f"Очищенных строк: {len(clean)}") print(f"Очищенный файл: {clean_path}") print(f"Всего выбросов: {len(records)}") print(f"Отчёт: {report}") return 0 if __name__ == "__main__": raise SystemExit(main())