Найти корреляции в CSV
Строит матрицу корреляции числовых колонок и показывает самые сильные пары.
Что делает скрипт
Скрипт приводит колонки к числам, отбрасывает полностью пустые и считает Pearson, Spearman или Kendall. Матрица сохраняется в CSV, а топ пар по модулю коэффициента выводится на экран и может быть записан отдельно. Пропуски учитываются попарно.
- Корреляция не доказывает причинность. Для категориальных колонок используйте другие методы.
Быстрый старт
python csv_correlation.py --input data.csv --output correlation.csv
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python csv_correlation.py --input data.csv --method spearman --top 5python csv_correlation.py --input metrics.csv --columns price,qty,rating --pairs pairs.csv --force
Что понадобится
winget install Python.Python.3.12
brew install python
sudo apt install python3
py -m pip install pandas
python3 -m pip install pandas
python3 -m pip install pandas
csv_correlation.py
#!/usr/bin/env python3
"""Матрица корреляции числовых колонок CSV."""
from __future__ import annotations
import argparse
from pathlib import Path
import pandas as pd
def split_columns(value: str) -> list[str]:
return [item.strip() for item in value.split(",") if item.strip()]
def main() -> int:
parser = argparse.ArgumentParser(description="Корреляция колонок CSV")
parser.add_argument("--input", type=Path, required=True, help="Исходный CSV")
parser.add_argument("--output", type=Path, default=Path("correlation.csv"), help="Матрица корреляции")
parser.add_argument("--pairs", type=Path, help="CSV с топом пар")
parser.add_argument("--columns", default="", help="Колонки через запятую")
parser.add_argument("--method", choices=["pearson", "spearman", "kendall"], default="pearson", help="Метод")
parser.add_argument("--top", type=int, default=10, help="Сколько пар показать")
parser.add_argument("--force", action="store_true", help="Перезаписать выходные файлы")
args = parser.parse_args()
source = args.input.expanduser().resolve()
target = args.output.expanduser().resolve()
if not source.is_file():
parser.error(f"Файл не найден: {source}")
if source == target:
parser.error("Выходной файл не должен совпадать с исходным")
outputs = [target]
if args.pairs:
outputs.append(args.pairs.expanduser().resolve())
if len(set(outputs)) != len(outputs):
parser.error("Выходные файлы не должны совпадать")
for path in outputs:
if path.exists() and not args.force:
parser.error(f"Файл уже существует: {path}. Добавьте --force")
if args.top < 1:
parser.error("--top должен быть положительным")
frame = pd.read_csv(source, encoding="utf-8-sig")
columns = split_columns(args.columns)
if columns:
missing = [name for name in columns if name not in frame.columns]
if missing:
parser.error("Нет колонок: " + ", ".join(missing))
numeric = frame[columns].apply(pd.to_numeric, errors="coerce")
else:
numeric = frame.apply(pd.to_numeric, errors="coerce")
numeric = numeric.dropna(axis=1, how="all")
if numeric.shape[1] < 2:
parser.error("Нужно минимум две числовые колонки")
matrix = numeric.corr(method=args.method)
target.parent.mkdir(parents=True, exist_ok=True)
matrix.to_csv(target, encoding="utf-8-sig")
pairs = []
names = list(matrix.columns)
for first in range(len(names)):
for second in range(first + 1, len(names)):
value = matrix.iloc[first, second]
if pd.notna(value):
pairs.append({
"column_a": names[first],
"column_b": names[second],
"correlation": round(float(value), 6),
"abs_correlation": round(abs(float(value)), 6),
})
pairs.sort(key=lambda item: item["abs_correlation"], reverse=True)
top = pairs[: args.top]
if args.pairs:
pairs_path = args.pairs.expanduser().resolve()
pairs_path.parent.mkdir(parents=True, exist_ok=True)
pd.DataFrame(pairs, columns=["column_a", "column_b", "correlation", "abs_correlation"]).to_csv(
pairs_path, index=False, encoding="utf-8-sig"
)
print(f"Пары: {pairs_path}")
print(f"Колонок: {numeric.shape[1]}")
print("Сильные пары:")
for item in top:
print(f" {item['column_a']} - {item['column_b']}: {item['correlation']}")
print(f"Матрица: {target}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.