exploradata 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.
@@ -0,0 +1,25 @@
1
+ """exploradata — ferramentas simples e composáveis para exploração de DataFrames.
2
+
3
+ Uso rápido:
4
+ import exploradata as xd
5
+
6
+ xd.profile(df) # relatório completo
7
+ xd.unique_values(df, "cidade") # únicos de uma coluna
8
+ xd.missing(df) # nulos ranqueados
9
+ """
10
+
11
+ from .overview import summary, peek, detect_types
12
+ from .quality import missing, duplicates, outliers, text_issues
13
+ from .columns import unique_values, cardinality, describe_numeric, describe_categorical
14
+ from .relations import correlation, high_correlations, constant_columns
15
+ from .report import profile, compare
16
+
17
+ __version__ = "0.1.0"
18
+
19
+ __all__ = [
20
+ "summary", "peek", "detect_types",
21
+ "missing", "duplicates", "outliers", "text_issues",
22
+ "unique_values", "cardinality", "describe_numeric", "describe_categorical",
23
+ "correlation", "high_correlations", "constant_columns",
24
+ "profile", "compare",
25
+ ]
exploradata/columns.py ADDED
@@ -0,0 +1,119 @@
1
+ """Análise por coluna: valores únicos, estatísticas e distribuição."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pandas as pd
6
+ import numpy as np
7
+
8
+
9
+ def unique_values(
10
+ df: pd.DataFrame,
11
+ column: str | None = None,
12
+ top: int = 20,
13
+ verbose: bool = False,
14
+ ) -> pd.DataFrame | dict[str, pd.DataFrame]:
15
+ """Valores únicos com frequência e percentual.
16
+
17
+ Se `column` for informada, retorna um DataFrame com os `top` valores
18
+ mais frequentes daquela coluna. Caso contrário, retorna um dict
19
+ {coluna: DataFrame} para todas as colunas.
20
+
21
+ Parameters
22
+ ----------
23
+ top : int
24
+ Quantos valores mais frequentes retornar (use None para todos).
25
+ verbose : bool
26
+ Se True, imprime os resultados formatados.
27
+ """
28
+ def _one(col: str) -> pd.DataFrame:
29
+ vc = df[col].value_counts(dropna=False)
30
+ out = pd.DataFrame({
31
+ "valor": vc.index,
32
+ "frequencia": vc.values,
33
+ "pct": (vc.values / len(df) * 100).round(2) if len(df) else 0.0,
34
+ })
35
+ if top is not None:
36
+ out = out.head(top)
37
+ return out.reset_index(drop=True)
38
+
39
+ if column is not None:
40
+ if column not in df.columns:
41
+ raise KeyError(f"Coluna '{column}' não existe no DataFrame")
42
+ result = _one(column)
43
+ if verbose:
44
+ n_uniq = df[column].nunique(dropna=True)
45
+ print(f"\n=== {column} ({n_uniq} valores únicos) ===")
46
+ print(result.to_string(index=False))
47
+ return result
48
+
49
+ results = {col: _one(col) for col in df.columns}
50
+ if verbose:
51
+ for col, res in results.items():
52
+ n_uniq = df[col].nunique(dropna=True)
53
+ print(f"\n=== {col} ({n_uniq} valores únicos) ===")
54
+ print(res.to_string(index=False))
55
+ return results
56
+
57
+
58
+ def cardinality(df: pd.DataFrame) -> pd.DataFrame:
59
+ """Cardinalidade por coluna, com classificação heurística.
60
+
61
+ Ajuda a identificar IDs (cardinalidade ~100%), categorias (baixa)
62
+ e colunas constantes.
63
+ """
64
+ n = len(df)
65
+ rows = []
66
+ for col in df.columns:
67
+ uniq = df[col].nunique(dropna=True)
68
+ pct = round(uniq / n * 100, 2) if n else 0.0
69
+ if uniq <= 1:
70
+ kind = "constante"
71
+ elif pct >= 99:
72
+ kind = "provavel_id"
73
+ elif pct >= 50:
74
+ kind = "alta_cardinalidade"
75
+ elif uniq <= 20:
76
+ kind = "categoria"
77
+ else:
78
+ kind = "intermediaria"
79
+ rows.append({
80
+ "coluna": col, "unicos": uniq,
81
+ "cardinalidade_pct": pct, "classificacao": kind,
82
+ })
83
+ return pd.DataFrame(rows).sort_values(
84
+ "cardinalidade_pct", ascending=False
85
+ ).reset_index(drop=True)
86
+
87
+
88
+ def describe_numeric(df: pd.DataFrame) -> pd.DataFrame:
89
+ """Estatísticas descritivas das colunas numéricas, incluindo skew e kurtosis."""
90
+ num = df.select_dtypes(include=np.number)
91
+ if num.empty:
92
+ return pd.DataFrame()
93
+
94
+ desc = num.describe(percentiles=[0.01, 0.05, 0.25, 0.5, 0.75, 0.95, 0.99]).T
95
+ desc["skewness"] = num.skew()
96
+ desc["kurtosis"] = num.kurtosis()
97
+ desc["nulos"] = num.isna().sum()
98
+ return desc.round(4).reset_index(names="coluna")
99
+
100
+
101
+ def describe_categorical(df: pd.DataFrame, top: int = 3) -> pd.DataFrame:
102
+ """Estatísticas das colunas categóricas/texto: moda e valores mais frequentes."""
103
+ cat = df.select_dtypes(include=["object", "string", "category"])
104
+ rows = []
105
+ for col in cat.columns:
106
+ s = df[col].dropna()
107
+ vc = s.value_counts()
108
+ top_vals = "; ".join(
109
+ f"{v} ({c})" for v, c in vc.head(top).items()
110
+ )
111
+ rows.append({
112
+ "coluna": col,
113
+ "unicos": s.nunique(),
114
+ "moda": vc.index[0] if len(vc) else None,
115
+ "freq_moda": int(vc.iloc[0]) if len(vc) else 0,
116
+ f"top_{top}": top_vals,
117
+ "nulos": int(df[col].isna().sum()),
118
+ })
119
+ return pd.DataFrame(rows)
@@ -0,0 +1,124 @@
1
+ """Visão geral do dataset: resumo, amostragem e detecção de tipos reais."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pandas as pd
6
+ import numpy as np
7
+
8
+
9
+ def summary(df: pd.DataFrame, verbose: bool = False) -> pd.DataFrame:
10
+ """Resumo geral do DataFrame: um df.info() melhorado.
11
+
12
+ Retorna um DataFrame com uma linha por coluna contendo tipo, nulos,
13
+ únicos, cardinalidade e uso de memória.
14
+
15
+ Parameters
16
+ ----------
17
+ df : pd.DataFrame
18
+ verbose : bool
19
+ Se True, imprime também um cabeçalho com shape e memória total.
20
+ """
21
+ n_rows = len(df)
22
+ info = pd.DataFrame({
23
+ "coluna": df.columns,
24
+ "dtype": [str(t) for t in df.dtypes],
25
+ "nulos": df.isna().sum().values,
26
+ "pct_nulos": (df.isna().mean() * 100).round(2).values,
27
+ "unicos": df.nunique(dropna=True).values,
28
+ })
29
+ info["cardinalidade_pct"] = (
30
+ (info["unicos"] / n_rows * 100).round(2) if n_rows else 0.0
31
+ )
32
+ info["memoria_kb"] = (
33
+ df.memory_usage(deep=True, index=False).values / 1024
34
+ ).round(1)
35
+
36
+ if verbose:
37
+ total_mb = df.memory_usage(deep=True).sum() / 1024**2
38
+ print(f"Shape: {df.shape[0]} linhas x {df.shape[1]} colunas")
39
+ print(f"Memória total: {total_mb:.2f} MB")
40
+ print(f"Linhas duplicadas: {df.duplicated().sum()}")
41
+ print(info.to_string(index=False))
42
+
43
+ return info
44
+
45
+
46
+ def peek(df: pd.DataFrame, n: int = 5, random_state: int | None = None) -> pd.DataFrame:
47
+ """Amostragem inteligente: head + amostra aleatória + tail em um só DataFrame.
48
+
49
+ Adiciona uma coluna '_origem' indicando de onde cada linha veio.
50
+ """
51
+ n = min(n, len(df))
52
+ if len(df) == 0:
53
+ return df.copy()
54
+
55
+ head = df.head(n).copy()
56
+ head["_origem"] = "head"
57
+ tail = df.tail(n).copy()
58
+ tail["_origem"] = "tail"
59
+
60
+ middle_idx = df.index.difference(head.index).difference(tail.index)
61
+ sample_n = min(n, len(middle_idx))
62
+ if sample_n > 0:
63
+ sample = df.loc[middle_idx].sample(sample_n, random_state=random_state).copy()
64
+ sample["_origem"] = "amostra"
65
+ else:
66
+ sample = df.iloc[0:0].copy()
67
+ sample["_origem"] = pd.Series(dtype=str)
68
+
69
+ return pd.concat([head, sample, tail])
70
+
71
+
72
+ def detect_types(df: pd.DataFrame, sample_size: int = 1000) -> pd.DataFrame:
73
+ """Detecta o tipo 'real' de colunas object: números, datas ou booleanos disfarçados.
74
+
75
+ Retorna apenas as colunas com sugestão de conversão.
76
+ """
77
+ suggestions = []
78
+ bool_sets = [
79
+ {"0", "1"}, {"true", "false"}, {"sim", "nao", "não"},
80
+ {"yes", "no"}, {"s", "n"}, {"t", "f"},
81
+ ]
82
+
83
+ for col in df.columns:
84
+ s = df[col].dropna()
85
+ if len(s) == 0:
86
+ continue
87
+ if len(s) > sample_size:
88
+ s = s.sample(sample_size, random_state=0)
89
+
90
+ current = str(df[col].dtype)
91
+ suggestion = None
92
+
93
+ # 0/1 numéricos que parecem booleanos
94
+ if pd.api.types.is_numeric_dtype(s):
95
+ vals = set(pd.unique(s))
96
+ if vals.issubset({0, 1}) and len(vals) == 2:
97
+ suggestion = "bool (0/1)"
98
+ elif current in ("object", "string", "str"):
99
+ as_str = s.astype(str).str.strip().str.lower()
100
+ uniq = set(as_str.unique())
101
+
102
+ if any(uniq.issubset(b) for b in bool_sets):
103
+ suggestion = "bool"
104
+ else:
105
+ numeric = pd.to_numeric(
106
+ s.astype(str).str.replace(",", ".", regex=False),
107
+ errors="coerce",
108
+ )
109
+ if numeric.notna().mean() > 0.95:
110
+ suggestion = "numérico"
111
+ else:
112
+ with np.errstate(all="ignore"):
113
+ dates = pd.to_datetime(s, errors="coerce", format="mixed")
114
+ if dates.notna().mean() > 0.95:
115
+ suggestion = "datetime"
116
+
117
+ if suggestion:
118
+ suggestions.append({
119
+ "coluna": col,
120
+ "dtype_atual": current,
121
+ "tipo_sugerido": suggestion,
122
+ })
123
+
124
+ return pd.DataFrame(suggestions, columns=["coluna", "dtype_atual", "tipo_sugerido"])
exploradata/quality.py ADDED
@@ -0,0 +1,120 @@
1
+ """Qualidade dos dados: nulos, duplicatas, outliers e inconsistências de texto."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pandas as pd
6
+ import numpy as np
7
+
8
+
9
+ def missing(df: pd.DataFrame, sort: bool = True) -> pd.DataFrame:
10
+ """Contagem e percentual de valores nulos por coluna, ranqueados."""
11
+ out = pd.DataFrame({
12
+ "coluna": df.columns,
13
+ "nulos": df.isna().sum().values,
14
+ "pct_nulos": (df.isna().mean() * 100).round(2).values,
15
+ })
16
+ if sort:
17
+ out = out.sort_values("nulos", ascending=False).reset_index(drop=True)
18
+ return out
19
+
20
+
21
+ def duplicates(df: pd.DataFrame, subset: list[str] | None = None) -> pd.DataFrame:
22
+ """Linhas duplicadas — completas ou por subconjunto de colunas (ex.: chaves).
23
+
24
+ Retorna todas as ocorrências dos grupos duplicados (keep=False),
25
+ ordenadas para facilitar a comparação lado a lado.
26
+ """
27
+ mask = df.duplicated(subset=subset, keep=False)
28
+ dups = df[mask]
29
+ if len(dups) and subset:
30
+ dups = dups.sort_values(subset)
31
+ elif len(dups):
32
+ dups = dups.sort_values(list(df.columns))
33
+ return dups
34
+
35
+
36
+ def outliers(
37
+ df: pd.DataFrame,
38
+ method: str = "iqr",
39
+ threshold: float | None = None,
40
+ ) -> pd.DataFrame:
41
+ """Detecta outliers nas colunas numéricas.
42
+
43
+ Parameters
44
+ ----------
45
+ method : 'iqr' ou 'zscore'
46
+ threshold : fator do IQR (padrão 1.5) ou limite de z-score (padrão 3.0)
47
+ """
48
+ num = df.select_dtypes(include=np.number)
49
+ rows = []
50
+
51
+ for col in num.columns:
52
+ s = num[col].dropna()
53
+ if len(s) < 4:
54
+ continue
55
+
56
+ if method == "iqr":
57
+ k = 1.5 if threshold is None else threshold
58
+ q1, q3 = s.quantile(0.25), s.quantile(0.75)
59
+ iqr = q3 - q1
60
+ low, high = q1 - k * iqr, q3 + k * iqr
61
+ elif method == "zscore":
62
+ k = 3.0 if threshold is None else threshold
63
+ std = s.std()
64
+ if std == 0 or np.isnan(std):
65
+ continue
66
+ mean = s.mean()
67
+ low, high = mean - k * std, mean + k * std
68
+ else:
69
+ raise ValueError("method deve ser 'iqr' ou 'zscore'")
70
+
71
+ mask = (s < low) | (s > high)
72
+ n_out = int(mask.sum())
73
+ rows.append({
74
+ "coluna": col,
75
+ "n_outliers": n_out,
76
+ "pct_outliers": round(n_out / len(s) * 100, 2),
77
+ "limite_inferior": round(float(low), 4),
78
+ "limite_superior": round(float(high), 4),
79
+ "min": round(float(s.min()), 4),
80
+ "max": round(float(s.max()), 4),
81
+ })
82
+
83
+ cols = ["coluna", "n_outliers", "pct_outliers", "limite_inferior",
84
+ "limite_superior", "min", "max"]
85
+ return pd.DataFrame(rows, columns=cols).sort_values(
86
+ "n_outliers", ascending=False
87
+ ).reset_index(drop=True)
88
+
89
+
90
+ def text_issues(df: pd.DataFrame) -> pd.DataFrame:
91
+ """Inconsistências em colunas de texto que inflam a contagem de únicos.
92
+
93
+ Detecta espaços extras nas pontas e variações de capitalização
94
+ ('SP' vs 'sp' vs ' SP').
95
+ """
96
+ rows = []
97
+ text_cols = df.select_dtypes(include=["object", "string"]).columns
98
+
99
+ for col in text_cols:
100
+ s = df[col].dropna().astype(str)
101
+ if len(s) == 0:
102
+ continue
103
+
104
+ n_whitespace = int((s != s.str.strip()).sum())
105
+ uniq_raw = s.nunique()
106
+ uniq_norm = s.str.strip().str.lower().nunique()
107
+ n_case_variants = uniq_raw - uniq_norm
108
+
109
+ if n_whitespace or n_case_variants:
110
+ rows.append({
111
+ "coluna": col,
112
+ "valores_com_espacos": n_whitespace,
113
+ "unicos_brutos": uniq_raw,
114
+ "unicos_normalizados": uniq_norm,
115
+ "variantes_redundantes": n_case_variants,
116
+ })
117
+
118
+ cols = ["coluna", "valores_com_espacos", "unicos_brutos",
119
+ "unicos_normalizados", "variantes_redundantes"]
120
+ return pd.DataFrame(rows, columns=cols)
@@ -0,0 +1,87 @@
1
+ """Relações entre colunas: correlação, redundância e colunas constantes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pandas as pd
6
+ import numpy as np
7
+
8
+
9
+ def correlation(df: pd.DataFrame, method: str = "pearson") -> pd.DataFrame:
10
+ """Matriz de correlação das colunas numéricas.
11
+
12
+ Parameters
13
+ ----------
14
+ method : 'pearson', 'spearman' ou 'kendall'
15
+ """
16
+ num = df.select_dtypes(include=np.number)
17
+ if num.shape[1] < 2:
18
+ return pd.DataFrame()
19
+ return num.corr(method=method).round(4)
20
+
21
+
22
+ def high_correlations(
23
+ df: pd.DataFrame,
24
+ threshold: float = 0.9,
25
+ method: str = "pearson",
26
+ ) -> pd.DataFrame:
27
+ """Pares de colunas com |correlação| acima do threshold — candidatas a redundância."""
28
+ corr = correlation(df, method=method)
29
+ if corr.empty:
30
+ return pd.DataFrame(columns=["coluna_a", "coluna_b", "correlacao"])
31
+
32
+ pairs = []
33
+ cols = corr.columns
34
+ for i in range(len(cols)):
35
+ for j in range(i + 1, len(cols)):
36
+ val = corr.iloc[i, j]
37
+ if pd.notna(val) and abs(val) >= threshold:
38
+ pairs.append({
39
+ "coluna_a": cols[i],
40
+ "coluna_b": cols[j],
41
+ "correlacao": round(float(val), 4),
42
+ })
43
+
44
+ out = pd.DataFrame(pairs, columns=["coluna_a", "coluna_b", "correlacao"])
45
+ if len(out):
46
+ out = out.reindex(
47
+ out["correlacao"].abs().sort_values(ascending=False).index
48
+ ).reset_index(drop=True)
49
+ return out
50
+
51
+
52
+ def constant_columns(df: pd.DataFrame, threshold: float = 0.99) -> pd.DataFrame:
53
+ """Colunas constantes ou quase constantes (candidatas a exclusão).
54
+
55
+ Parameters
56
+ ----------
57
+ threshold : float
58
+ Fração mínima do valor dominante para marcar como quase constante.
59
+ """
60
+ rows = []
61
+ n = len(df)
62
+ if n == 0:
63
+ return pd.DataFrame(
64
+ columns=["coluna", "valor_dominante", "pct_dominante", "status"]
65
+ )
66
+
67
+ for col in df.columns:
68
+ vc = df[col].value_counts(dropna=False)
69
+ if len(vc) == 0:
70
+ continue
71
+ dominant_pct = vc.iloc[0] / n
72
+ if len(vc) == 1:
73
+ status = "constante"
74
+ elif dominant_pct >= threshold:
75
+ status = "quase_constante"
76
+ else:
77
+ continue
78
+ rows.append({
79
+ "coluna": col,
80
+ "valor_dominante": vc.index[0],
81
+ "pct_dominante": round(dominant_pct * 100, 2),
82
+ "status": status,
83
+ })
84
+
85
+ return pd.DataFrame(
86
+ rows, columns=["coluna", "valor_dominante", "pct_dominante", "status"]
87
+ )
exploradata/report.py ADDED
@@ -0,0 +1,134 @@
1
+ """Relatório consolidado e comparação entre DataFrames."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pandas as pd
6
+ import numpy as np
7
+
8
+ from .overview import summary, detect_types
9
+ from .quality import missing, outliers, text_issues
10
+ from .columns import cardinality, describe_numeric, describe_categorical
11
+ from .relations import high_correlations, constant_columns
12
+
13
+
14
+ def profile(df: pd.DataFrame, verbose: bool = True) -> dict[str, pd.DataFrame]:
15
+ """Roda todas as análises e retorna um dicionário de DataFrames.
16
+
17
+ Chaves: summary, missing, cardinality, numeric, categorical,
18
+ outliers, text_issues, high_correlations, constant_columns,
19
+ type_suggestions.
20
+
21
+ Se verbose=True, imprime um relatório organizado.
22
+ """
23
+ report = {
24
+ "summary": summary(df),
25
+ "missing": missing(df),
26
+ "cardinality": cardinality(df),
27
+ "numeric": describe_numeric(df),
28
+ "categorical": describe_categorical(df),
29
+ "outliers": outliers(df),
30
+ "text_issues": text_issues(df),
31
+ "high_correlations": high_correlations(df),
32
+ "constant_columns": constant_columns(df),
33
+ "type_suggestions": detect_types(df),
34
+ }
35
+
36
+ if verbose:
37
+ _print_report(df, report)
38
+
39
+ return report
40
+
41
+
42
+ def _print_report(df: pd.DataFrame, report: dict[str, pd.DataFrame]) -> None:
43
+ sep = "=" * 70
44
+ print(sep)
45
+ print("RELATÓRIO DE EXPLORAÇÃO")
46
+ print(sep)
47
+ print(f"Shape: {df.shape[0]} linhas x {df.shape[1]} colunas")
48
+ print(f"Memória: {df.memory_usage(deep=True).sum() / 1024**2:.2f} MB")
49
+ print(f"Linhas duplicadas: {df.duplicated().sum()}")
50
+
51
+ sections = [
52
+ ("VISÃO GERAL POR COLUNA", "summary"),
53
+ ("VALORES NULOS", "missing"),
54
+ ("CARDINALIDADE", "cardinality"),
55
+ ("NUMÉRICAS", "numeric"),
56
+ ("CATEGÓRICAS", "categorical"),
57
+ ("OUTLIERS (IQR)", "outliers"),
58
+ ("INCONSISTÊNCIAS DE TEXTO", "text_issues"),
59
+ ("CORRELAÇÕES ALTAS (|r| >= 0.9)", "high_correlations"),
60
+ ("COLUNAS CONSTANTES / QUASE CONSTANTES", "constant_columns"),
61
+ ("SUGESTÕES DE CONVERSÃO DE TIPO", "type_suggestions"),
62
+ ]
63
+ for title, key in sections:
64
+ data = report[key]
65
+ print(f"\n--- {title} ---")
66
+ if data is None or len(data) == 0:
67
+ print("(nada encontrado)")
68
+ else:
69
+ print(data.to_string(index=False))
70
+ print("\n" + sep)
71
+
72
+
73
+ def compare(
74
+ df_a: pd.DataFrame,
75
+ df_b: pd.DataFrame,
76
+ names: tuple[str, str] = ("A", "B"),
77
+ ) -> dict[str, pd.DataFrame]:
78
+ """Compara dois DataFrames: schema, shape e distribuição das numéricas.
79
+
80
+ Útil para validar cargas de dados (ex.: mês anterior vs mês atual).
81
+
82
+ Retorna dict com 'schema' e 'numeric_shift'.
83
+ """
84
+ na, nb = names
85
+
86
+ # --- Schema ---
87
+ cols = sorted(set(df_a.columns) | set(df_b.columns))
88
+ schema_rows = []
89
+ for col in cols:
90
+ in_a, in_b = col in df_a.columns, col in df_b.columns
91
+ dtype_a = str(df_a[col].dtype) if in_a else "-"
92
+ dtype_b = str(df_b[col].dtype) if in_b else "-"
93
+ if not in_a:
94
+ status = f"apenas_em_{nb}"
95
+ elif not in_b:
96
+ status = f"apenas_em_{na}"
97
+ elif dtype_a != dtype_b:
98
+ status = "dtype_diferente"
99
+ else:
100
+ status = "ok"
101
+ schema_rows.append({
102
+ "coluna": col, f"dtype_{na}": dtype_a,
103
+ f"dtype_{nb}": dtype_b, "status": status,
104
+ })
105
+ schema = pd.DataFrame(schema_rows)
106
+
107
+ # --- Distribuição das numéricas em comum ---
108
+ common_num = [
109
+ c for c in df_a.columns
110
+ if c in df_b.columns
111
+ and pd.api.types.is_numeric_dtype(df_a[c])
112
+ and pd.api.types.is_numeric_dtype(df_b[c])
113
+ ]
114
+ shift_rows = []
115
+ for col in common_num:
116
+ sa, sb = df_a[col].dropna(), df_b[col].dropna()
117
+ mean_a = float(sa.mean()) if len(sa) else np.nan
118
+ mean_b = float(sb.mean()) if len(sb) else np.nan
119
+ delta = (
120
+ round((mean_b - mean_a) / abs(mean_a) * 100, 2)
121
+ if mean_a not in (0, np.nan) and not np.isnan(mean_a)
122
+ else np.nan
123
+ )
124
+ shift_rows.append({
125
+ "coluna": col,
126
+ f"media_{na}": round(mean_a, 4),
127
+ f"media_{nb}": round(mean_b, 4),
128
+ "delta_media_pct": delta,
129
+ f"nulos_{na}_pct": round(df_a[col].isna().mean() * 100, 2),
130
+ f"nulos_{nb}_pct": round(df_b[col].isna().mean() * 100, 2),
131
+ })
132
+ numeric_shift = pd.DataFrame(shift_rows)
133
+
134
+ return {"schema": schema, "numeric_shift": numeric_shift}
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.4
2
+ Name: exploradata
3
+ Version: 0.1.0
4
+ Summary: Ferramentas simples e composáveis para exploração de DataFrames (EDA)
5
+ Author-email: Anna Gatelli <anna.gatelli@bateleur.com.br>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/anna-gatelli/exploradata
8
+ Keywords: eda,pandas,data-exploration,data-quality
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: pandas>=1.5
17
+ Requires-Dist: numpy>=1.23
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest>=7.0; extra == "dev"
20
+ Dynamic: license-file
21
+
22
+ # exploradata
23
+
24
+ Ferramentas simples e composáveis para exploração de DataFrames pandas (EDA).
25
+
26
+ Todas as funções **retornam DataFrames** — dá para filtrar, ordenar, exportar e encadear. Quando você só quer olhar, use `verbose=True` ou a função `profile()`.
27
+
28
+ ## Instalação
29
+
30
+ ```bash
31
+ pip install git+https://github.com/anna-gatelli/exploradata.git
32
+ ```
33
+
34
+ Ou, para desenvolvimento local:
35
+
36
+ ```bash
37
+ git clone https://github.com/anna-gatelli/exploradata.git
38
+ cd exploradata
39
+ pip install -e ".[dev]"
40
+ ```
41
+
42
+ ## Uso rápido
43
+
44
+ ```python
45
+ import pandas as pd
46
+ import exploradata as xd
47
+
48
+ df = pd.read_csv("dados.csv")
49
+
50
+ # Relatório completo de uma vez
51
+ report = xd.profile(df)
52
+
53
+ # Ou função por função:
54
+ xd.unique_values(df, "cidade") # únicos com frequência e %
55
+ xd.summary(df) # df.info() melhorado
56
+ xd.missing(df) # nulos ranqueados
57
+ xd.outliers(df) # outliers por IQR (ou method="zscore")
58
+ xd.peek(df) # head + amostra aleatória + tail
59
+ ```
60
+
61
+ ## Funções
62
+
63
+ ### Visão geral
64
+ | Função | O que faz |
65
+ |---|---|
66
+ | `summary(df)` | Tipo, nulos, únicos, cardinalidade e memória por coluna |
67
+ | `peek(df, n=5)` | head + amostra aleatória + tail em um só DataFrame |
68
+ | `detect_types(df)` | Detecta números, datas e booleanos "disfarçados" em colunas de texto |
69
+
70
+ ### Qualidade
71
+ | Função | O que faz |
72
+ |---|---|
73
+ | `missing(df)` | Nulos por coluna (contagem e %), ranqueados |
74
+ | `duplicates(df, subset=None)` | Linhas duplicadas, completas ou por chave |
75
+ | `outliers(df, method="iqr")` | Outliers por IQR ou z-score nas numéricas |
76
+ | `text_issues(df)` | Espaços extras e variações de capitalização que inflam os únicos |
77
+
78
+ ### Por coluna
79
+ | Função | O que faz |
80
+ |---|---|
81
+ | `unique_values(df, coluna, top=20)` | Valores únicos com frequência e % (sem coluna: todas) |
82
+ | `cardinality(df)` | % de únicos + classificação (id, categoria, constante...) |
83
+ | `describe_numeric(df)` | Estatísticas + percentis + skewness + kurtosis |
84
+ | `describe_categorical(df)` | Moda, frequências e top valores |
85
+
86
+ ### Relações
87
+ | Função | O que faz |
88
+ |---|---|
89
+ | `correlation(df, method="pearson")` | Matriz de correlação (pearson/spearman/kendall) |
90
+ | `high_correlations(df, threshold=0.9)` | Pares de colunas possivelmente redundantes |
91
+ | `constant_columns(df)` | Colunas constantes ou quase constantes |
92
+
93
+ ### Consolidado
94
+ | Função | O que faz |
95
+ |---|---|
96
+ | `profile(df)` | Roda tudo e imprime relatório organizado; retorna dict de DataFrames |
97
+ | `compare(df_a, df_b)` | Compara schema e distribuições — útil pra validar cargas |
98
+
99
+ ## Exemplo de saída
100
+
101
+ ```python
102
+ >>> xd.unique_values(df, "cidade")
103
+ valor frequencia pct
104
+ 0 SP 38 38.00
105
+ 1 RJ 25 25.00
106
+ 2 BH 20 20.00
107
+ 3 sp 10 10.00
108
+ 4 " SP" 7 7.00
109
+ ```
110
+
111
+ Repare que `text_issues(df)` avisaria que "SP", "sp" e " SP" provavelmente são o mesmo valor.
112
+
113
+ ## Rodando os testes
114
+
115
+ ```bash
116
+ pytest
117
+ ```
118
+
119
+ ## Licença
120
+
121
+ MIT
@@ -0,0 +1,11 @@
1
+ exploradata/__init__.py,sha256=14Jwy7-csAfYy_ZorH5cN8Vj6jUwRruWyXZQD8AMhvk,931
2
+ exploradata/columns.py,sha256=-aosFNksvEycwyzdXG-gplcTukzfGLPnz3x5wjx38bM,3951
3
+ exploradata/overview.py,sha256=sS2CD2hTEESsi-Er7VtiNVu7GsZTWfC0gQnSaAiQBfU,4151
4
+ exploradata/quality.py,sha256=4TjTkAoMkl1N8wJYJNfnALKsciMEUfsCqbHOf6CcPhE,3925
5
+ exploradata/relations.py,sha256=pDriGdHumwB-lFDFc7O9s4Lj6eJZ71RA9kkRmLsipSY,2601
6
+ exploradata/report.py,sha256=okWMcagOshh_242YEQiu3k3g1Z79Ajcz4xgJTRJlzew,4559
7
+ exploradata-0.1.0.dist-info/licenses/LICENSE,sha256=G4odqSQVC6_QZaiTigy9iHr0lPotCeEHIPiqfjYbWxE,1084
8
+ exploradata-0.1.0.dist-info/METADATA,sha256=a_m27BER0WHK67G4FeMDdNemF-YyAiL3JW3hLf5zJfY,3756
9
+ exploradata-0.1.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
10
+ exploradata-0.1.0.dist-info/top_level.txt,sha256=dCcUklJac8w18iGn32bDTZNCOX1-xUXt7nSSFkMSH6U,12
11
+ exploradata-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (83.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Anna Elisa Petersen Gatelli
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ exploradata