edapy-tools 0.1.2__tar.gz → 0.2.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: edapy-tools
3
- Version: 0.1.2
3
+ Version: 0.2.0
4
4
  Summary: Fast, lightweight, and intuitive Exploratory Data Analysis (EDA) toolkit for pandas.
5
5
  Author: Abdulaziz Mohamed
6
6
  License: MIT
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "edapy-tools"
3
- version = "0.1.2"
3
+ version = "0.2.0"
4
4
  description = "Fast, lightweight, and intuitive Exploratory Data Analysis (EDA) toolkit for pandas."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.7"
@@ -2,5 +2,5 @@ from .load_clean import load
2
2
  from .stats import stats
3
3
  from .summary import summary
4
4
 
5
- __version__ = "0.1.2"
5
+ __version__ = "0.2.0"
6
6
  __all__ = ["load", "stats", "summary"]
@@ -0,0 +1,100 @@
1
+ from __future__ import annotations
2
+ from pathlib import Path
3
+ from typing import Union
4
+ import numpy as np
5
+ import pandas as pd
6
+
7
+ _MISSING_TOKENS = {
8
+ "",
9
+ "na",
10
+ "n/a",
11
+ "nan",
12
+ "null",
13
+ "none",
14
+ "nil",
15
+ "-",
16
+ "--",
17
+ "?",
18
+ "unknown",
19
+ }
20
+
21
+
22
+ def _read_any_file(file_path: Union[str, Path, pd.DataFrame]) -> pd.DataFrame:
23
+ if isinstance(file_path, pd.DataFrame):
24
+ return file_path.copy()
25
+
26
+ path = Path(file_path)
27
+ if not path.exists():
28
+ raise FileNotFoundError(f"File not found: {path}")
29
+
30
+ suffix = path.suffix.lower()
31
+
32
+ if suffix in {".xlsx", ".xls"}:
33
+ try:
34
+ return pd.read_excel(path)
35
+ except ImportError as exc:
36
+ raise ImportError(
37
+ "Reading Excel files requires 'openpyxl'. Install it via: pip install"
38
+ " openpyxl"
39
+ ) from exc
40
+
41
+ if suffix == ".json":
42
+ return pd.read_json(path)
43
+
44
+ last_err = None
45
+ for enc in ("utf-8", "utf-8-sig", "cp1256", "latin1"):
46
+ try:
47
+ df = pd.read_csv(path, encoding=enc)
48
+ if df.shape[1] == 1:
49
+ df_auto = pd.read_csv(path, encoding=enc, sep=None, engine="python")
50
+ if df_auto.shape[1] > 1:
51
+ return df_auto
52
+ return df
53
+ except Exception as err:
54
+ last_err = err
55
+
56
+ raise ValueError(f"Could not decode or parse '{path}': {last_err}")
57
+
58
+
59
+ def load(
60
+ file_path: Union[str, Path, pd.DataFrame],
61
+ preview: bool = False,
62
+ head_rows: int = 5,
63
+ ) -> pd.DataFrame:
64
+ df = _read_any_file(file_path)
65
+
66
+ # Clean column names
67
+ df.columns = [str(c).strip() for c in df.columns]
68
+
69
+ # Normalize hidden missing tokens in text columns
70
+ for col in df.select_dtypes(include=["object", "string"]).columns:
71
+ stripped = df[col].astype(str).str.strip()
72
+ mask = stripped.str.lower().isin(_MISSING_TOKENS) & df[col].notna()
73
+ if mask.any():
74
+ df.loc[mask, col] = np.nan
75
+
76
+ dups = int(df.duplicated().sum())
77
+ if dups > 0:
78
+ df = df.drop_duplicates().reset_index(drop=True)
79
+ print(f"Duplicates: {dups} -> Removed.")
80
+ else:
81
+ print("Duplicates: 0 -> Nothing removed.")
82
+
83
+ missing = df.isnull().sum()
84
+ total_missing = int(missing.sum())
85
+ print(f"Missing values: {total_missing}")
86
+ if total_missing > 0:
87
+ print(missing[missing > 0])
88
+
89
+ print(f"Shape: {df.shape[0]} rows x {df.shape[1]} columns")
90
+
91
+ if preview:
92
+ short_df = df.head(head_rows).copy()
93
+ short_df.columns = [
94
+ f"{str(c)[:18]}..." if len(str(c)) > 20 else str(c)
95
+ for c in short_df.columns
96
+ ]
97
+ print(f"\nPreview (first {head_rows} rows):")
98
+ print(short_df.to_string(index=False, max_cols=5))
99
+
100
+ return df
@@ -0,0 +1,164 @@
1
+ from __future__ import annotations
2
+ from typing import Any, Dict, Optional, Tuple
3
+ import numpy as np
4
+ import pandas as pd
5
+
6
+ _MISSING_TOKENS = {
7
+ "",
8
+ "na",
9
+ "n/a",
10
+ "nan",
11
+ "null",
12
+ "none",
13
+ "nil",
14
+ "-",
15
+ "--",
16
+ "?",
17
+ "unknown",
18
+ }
19
+
20
+
21
+ def _prepare_series(
22
+ s: pd.Series,
23
+ ) -> Tuple[pd.Series, str, Optional[Dict[str, int]]]:
24
+ """Convert any column (numeric, dirty numeric, bool, datetime, categorical) into a numeric series."""
25
+ if pd.api.types.is_bool_dtype(s):
26
+ return s.astype("float64"), "boolean (0/1)", None
27
+
28
+ if pd.api.types.is_numeric_dtype(s):
29
+ return pd.to_numeric(s, errors="coerce"), "numeric", None
30
+
31
+ if pd.api.types.is_datetime64_any_dtype(s):
32
+ days = (s - pd.Timestamp("1970-01-01")) / pd.Timedelta(days=1)
33
+ return pd.to_numeric(days, errors="coerce"), "datetime (days)", None
34
+
35
+ # Clean text missing tokens first
36
+ s_clean = s.copy()
37
+ non_null_mask = s_clean.notna()
38
+ stripped = s_clean[non_null_mask].astype(str).str.strip()
39
+ missing_mask = stripped.str.lower().isin(_MISSING_TOKENS)
40
+ if missing_mask.any():
41
+ s_clean.loc[stripped[missing_mask].index] = np.nan
42
+
43
+ valid = s_clean.dropna()
44
+ if len(valid) == 0:
45
+ return pd.Series(dtype="float64"), "empty", None
46
+
47
+ # Try cleaning dirty numbers like "$1,250.50", "45%", "(500)", "200 EGP"
48
+ cleaned_str = (
49
+ valid.astype(str)
50
+ .str.strip()
51
+ .str.replace(r"^\((.+)\)$", r"-\1", regex=True)
52
+ .str.replace(r"[,$€£¥%]", "", regex=True)
53
+ .str.replace(
54
+ r"\s*(egp|usd|sar|kwd|aed|eur|gbp|kg|km|kwh)$",
55
+ "",
56
+ case=False,
57
+ regex=True,
58
+ )
59
+ .str.strip()
60
+ )
61
+ parsed_num = pd.to_numeric(cleaned_str, errors="coerce")
62
+
63
+ if float(parsed_num.notna().mean()) >= 0.70:
64
+ full_str = (
65
+ s_clean.astype(str)
66
+ .str.strip()
67
+ .str.replace(r"^\((.+)\)$", r"-\1", regex=True)
68
+ .str.replace(r"[,$€£¥%]", "", regex=True)
69
+ .str.replace(
70
+ r"\s*(egp|usd|sar|kwd|aed|eur|gbp|kg|km|kwh)$",
71
+ "",
72
+ case=False,
73
+ regex=True,
74
+ )
75
+ .str.strip()
76
+ )
77
+ full_num = pd.to_numeric(full_str, errors="coerce")
78
+ return full_num, "numeric (cleaned)", None
79
+
80
+ # Try parsing date-like strings
81
+ sample_str = valid.astype(str).str.strip()
82
+ if sample_str.str.contains(r"[-/:]", regex=True).mean() >= 0.70:
83
+ parsed_dt = pd.to_datetime(sample_str, errors="coerce")
84
+ if float(parsed_dt.notna().mean()) >= 0.70:
85
+ full_dt = pd.to_datetime(s_clean, errors="coerce")
86
+ days = (full_dt - pd.Timestamp("1970-01-01")) / pd.Timedelta(days=1)
87
+ return pd.to_numeric(days, errors="coerce"), "datetime (days)", None
88
+
89
+ # Categorical / text auto-encoding
90
+ codes, uniques = pd.factorize(s_clean)
91
+ num_s = pd.Series(codes, index=s.index, dtype="float64").where(
92
+ s_clean.notna(), np.nan
93
+ )
94
+ mapping = {str(val): int(idx) for idx, val in enumerate(uniques[:5])}
95
+ return num_s, "categorical (auto-encoded)", mapping
96
+
97
+
98
+ def stats(
99
+ df: pd.DataFrame, column: str, decimals: int = 2, show: bool = True
100
+ ) -> Dict[str, Any]:
101
+ if column not in df.columns:
102
+ available = ", ".join(map(str, df.columns[:10]))
103
+ raise ValueError(
104
+ f"Column '{column}' not found. Available columns: [{available}]"
105
+ )
106
+
107
+ num_s, col_type, mapping = _prepare_series(df[column])
108
+ clean = num_s.dropna()
109
+
110
+ if len(clean) == 0:
111
+ result: Dict[str, Any] = {
112
+ "column": column,
113
+ "type": "empty",
114
+ "count": 0,
115
+ "sum": None,
116
+ "mean": None,
117
+ "median": None,
118
+ "q1": None,
119
+ "q3": None,
120
+ "iqr": None,
121
+ "lower_bound": None,
122
+ "upper_bound": None,
123
+ "outliers_count": 0,
124
+ }
125
+ if show:
126
+ print(f"\n--- Stats for '{column}' [empty column] ---")
127
+ return result
128
+
129
+ is_datetime = col_type.startswith("datetime")
130
+ total = None if is_datetime else round(float(clean.sum()), decimals)
131
+ mean = round(float(clean.mean()), decimals)
132
+ median = round(float(clean.median()), decimals)
133
+ q1 = round(float(clean.quantile(0.25)), decimals)
134
+ q3 = round(float(clean.quantile(0.75)), decimals)
135
+ iqr = round(q3 - q1, decimals)
136
+ lower = round(q1 - 1.5 * iqr, decimals)
137
+ upper = round(q3 + 1.5 * iqr, decimals)
138
+ outliers_count = int(((clean < lower) | (clean > upper)).sum())
139
+
140
+ result = {
141
+ "column": column,
142
+ "type": col_type,
143
+ "count": int(len(clean)),
144
+ "sum": total,
145
+ "mean": mean,
146
+ "median": median,
147
+ "q1": q1,
148
+ "q3": q3,
149
+ "iqr": iqr,
150
+ "lower_bound": lower,
151
+ "upper_bound": upper,
152
+ "outliers_count": outliers_count,
153
+ }
154
+
155
+ if show:
156
+ print(f"\n--- Stats for '{column}' [{col_type}] ---")
157
+ if mapping:
158
+ preview_map = ", ".join(f"{k}={v}" for k, v in mapping.items())
159
+ print(f"Encoding map (sample): {preview_map}")
160
+ for k, v in result.items():
161
+ if k not in ("column", "type"):
162
+ print(f" {k:<15}: {v}")
163
+
164
+ return result
@@ -0,0 +1,55 @@
1
+ from __future__ import annotations
2
+ from typing import List, Optional
3
+ import pandas as pd
4
+ from .stats import stats
5
+
6
+
7
+ def summary(
8
+ df: pd.DataFrame,
9
+ columns: Optional[List[str]] = None,
10
+ save_path: Optional[str] = "summary.csv",
11
+ decimals: int = 2,
12
+ show: bool = True,
13
+ ) -> pd.DataFrame:
14
+ cols = columns if columns is not None else list(df.columns)
15
+ rows = []
16
+
17
+ for col in cols:
18
+ res = stats(df, col, decimals=decimals, show=False)
19
+ rows.append({
20
+ "Column": col,
21
+ "Type": res["type"],
22
+ "Total": res["sum"] if res["sum"] is not None else "-",
23
+ "Mean": res["mean"] if res["mean"] is not None else "-",
24
+ "Median": res["median"] if res["median"] is not None else "-",
25
+ "Q1": res["q1"] if res["q1"] is not None else "-",
26
+ "Q3": res["q3"] if res["q3"] is not None else "-",
27
+ "IQR": res["iqr"] if res["iqr"] is not None else "-",
28
+ "Lower_Bound": (
29
+ res["lower_bound"] if res["lower_bound"] is not None else "-"
30
+ ),
31
+ "Upper_Bound": (
32
+ res["upper_bound"] if res["upper_bound"] is not None else "-"
33
+ ),
34
+ "Outliers": res["outliers_count"],
35
+ })
36
+
37
+ out = pd.DataFrame(rows)
38
+
39
+ if save_path:
40
+ out.to_csv(save_path, index=False)
41
+ print(f"\nSummary CSV saved to: {save_path}")
42
+
43
+ if show:
44
+ max_col = int(out["Column"].astype(str).str.len().max())
45
+ max_type = int(out["Type"].astype(str).str.len().max())
46
+ fmt = {
47
+ "Column": lambda x: f"{str(x):<{max_col}} ",
48
+ "Type": lambda x: f"{str(x):<{max_type}} ",
49
+ }
50
+ print()
51
+ print(
52
+ out.to_string(index=False, justify="left", col_space=3, formatters=fmt)
53
+ )
54
+
55
+ return out
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: edapy-tools
3
- Version: 0.1.2
3
+ Version: 0.2.0
4
4
  Summary: Fast, lightweight, and intuitive Exploratory Data Analysis (EDA) toolkit for pandas.
5
5
  Author: Abdulaziz Mohamed
6
6
  License: MIT
@@ -1,34 +0,0 @@
1
- from __future__ import annotations
2
- import pandas as pd
3
-
4
-
5
- def load(
6
- file_path: str, preview: bool = False, head_rows: int = 5
7
- ) -> pd.DataFrame:
8
- df = pd.read_csv(file_path)
9
-
10
- dups = int(df.duplicated().sum())
11
- if dups > 0:
12
- df = df.drop_duplicates().reset_index(drop=True)
13
- print(f"Duplicates: {dups} -> Removed.")
14
- else:
15
- print("Duplicates: 0 -> Nothing removed.")
16
-
17
- missing = df.isnull().sum()
18
- total_missing = int(missing.sum())
19
- print(f"Missing values: {total_missing}")
20
- if total_missing > 0:
21
- print(missing[missing > 0])
22
-
23
- print(f"Shape: {df.shape[0]} rows x {df.shape[1]} columns")
24
-
25
- if preview:
26
- short_df = df.head(head_rows).copy()
27
- short_df.columns = [
28
- f"{str(c)[:18]}..." if len(str(c)) > 20 else str(c)
29
- for c in short_df.columns
30
- ]
31
- print(f"\nPreview (first {head_rows} rows):")
32
- print(short_df.to_string(index=False, max_cols=5))
33
-
34
- return df
@@ -1,51 +0,0 @@
1
- import pandas as pd
2
-
3
-
4
- def _to_numeric(series: pd.Series, col_name: str) -> pd.Series:
5
- if pd.api.types.is_numeric_dtype(series):
6
- return series.dropna().astype(float)
7
-
8
- as_num = pd.to_numeric(series, errors="coerce")
9
- if as_num.notna().mean() >= 0.8:
10
- print(f"Note: '{col_name}' converted from text to numeric.")
11
- return as_num.dropna().astype(float)
12
-
13
- codes, uniques = pd.factorize(series.dropna(), sort=True)
14
- mapping = {val: idx for idx, val in enumerate(uniques)}
15
- print(f"Note: '{col_name}' is text -> encoded to numbers: {mapping}")
16
- return pd.Series(codes, index=series.dropna().index, dtype=float)
17
-
18
-
19
- def stats(
20
- df: pd.DataFrame, column: str, decimals: int = 2, show: bool = True
21
- ) -> dict:
22
- if column not in df.columns:
23
- raise KeyError(f"Column '{column}' not found.")
24
-
25
- s = _to_numeric(df[column], column)
26
- q1 = s.quantile(0.25)
27
- median = s.quantile(0.50)
28
- q3 = s.quantile(0.75)
29
- iqr = q3 - q1
30
- lower = q1 - 1.5 * iqr
31
- upper = q3 + 1.5 * iqr
32
- outliers = s[(s < lower) | (s > upper)]
33
-
34
- res = {
35
- "sum": round(float(s.sum()), decimals),
36
- "mean": round(float(s.mean()), decimals),
37
- "median": round(float(median), decimals),
38
- "q1": round(float(q1), decimals),
39
- "q3": round(float(q3), decimals),
40
- "iqr": round(float(iqr), decimals),
41
- "lower_bound": round(float(lower), decimals),
42
- "upper_bound": round(float(upper), decimals),
43
- "outliers_count": int(outliers.count()),
44
- }
45
-
46
- if show:
47
- print(f"\n--- {column} ---")
48
- for k, v in res.items():
49
- print(f"{k}: {v}")
50
-
51
- return res
@@ -1,46 +0,0 @@
1
- from __future__ import annotations
2
- from typing import List, Optional
3
- import pandas as pd
4
- from .stats import stats
5
-
6
-
7
- def summary(
8
- df: pd.DataFrame,
9
- columns: Optional[List[str]] = None,
10
- save_path: Optional[str] = "summary.csv",
11
- decimals: int = 2,
12
- show: bool = True,
13
- ) -> pd.DataFrame:
14
- cols = columns if columns is not None else list(df.columns)
15
- rows = []
16
-
17
- for col in cols:
18
- res = stats(df, col, decimals=decimals, show=False)
19
- rows.append({
20
- "Column": col,
21
- "Total": res["sum"],
22
- "Mean": res["mean"],
23
- "Median": res["median"],
24
- "Q1": res["q1"],
25
- "Q3": res["q3"],
26
- "IQR": res["iqr"],
27
- "Lower_Bound": res["lower_bound"],
28
- "Upper_Bound": res["upper_bound"],
29
- "Outliers": res["outliers_count"],
30
- })
31
-
32
- out = pd.DataFrame(rows)
33
-
34
- if save_path:
35
- out.to_csv(save_path, index=False)
36
- print(f"\nSummary CSV saved to: {save_path}")
37
-
38
- if show:
39
- max_len = int(out["Column"].astype(str).str.len().max())
40
- fmt = {"Column": lambda x: f"{str(x):<{max_len}} "}
41
- print()
42
- print(
43
- out.to_string(index=False, justify="left", col_space=3, formatters=fmt)
44
- )
45
-
46
- return out
File without changes
File without changes
File without changes