TanU21 commited on
Commit
460718f
·
verified ·
1 Parent(s): 0c6dea9

Update preprocessing.py

Browse files

Change standardization function

Files changed (1) hide show
  1. preprocessing.py +19 -9
preprocessing.py CHANGED
@@ -16,26 +16,36 @@ def data_quality(df: pd.DataFrame):
16
 
17
  def standardize_data_types(df: pd.DataFrame) -> pd.DataFrame:
18
  for col in df.columns:
 
19
  if df[col].isin([True, False]).all():
20
  continue
21
- if df[col].dtype == 'object' and df[col].str.replace('.', '', 1).str.isnumeric().all():
22
- df[col] = pd.to_numeric(df[col], errors='ignore')
 
 
 
 
 
 
 
23
  try:
24
- df[col] = pd.to_datetime(df[col], errors='coerce')
25
- if df[col].notna().sum() == 0:
26
- df[col] = df[col].astype(str)
27
  except Exception:
28
  pass
 
 
29
  try:
30
  if df[col].apply(lambda x: isinstance(x, str) and x.startswith("[") and x.endswith("]")).all():
31
  df[col] = df[col].apply(json.loads)
32
  except Exception:
33
  pass
34
- if df[col].dtype == 'object' and df[col].dropna().isin(["TRUE", "FALSE"]).all():
 
 
35
  df[col] = df[col].map({"TRUE": True, "FALSE": False})
36
- if df[col].dtype == 'object':
37
- df[col] = df[col].astype(str)
38
- df.fillna("", inplace=True)
39
  return df
40
 
41
  def handle_missing_data(df: pd.DataFrame) -> pd.DataFrame:
 
16
 
17
  def standardize_data_types(df: pd.DataFrame) -> pd.DataFrame:
18
  for col in df.columns:
19
+ # Skip boolean columns
20
  if df[col].isin([True, False]).all():
21
  continue
22
+
23
+ # Attempt numeric conversion
24
+ if df[col].dtype == 'object':
25
+ try:
26
+ df[col] = pd.to_numeric(df[col], errors='coerce')
27
+ except Exception:
28
+ pass
29
+
30
+ # Attempt datetime conversion
31
  try:
32
+ temp_col = pd.to_datetime(df[col], errors='coerce')
33
+ if temp_col.notna().sum() > 0:
34
+ df[col] = temp_col
35
  except Exception:
36
  pass
37
+
38
+ # JSON list/dict conversion
39
  try:
40
  if df[col].apply(lambda x: isinstance(x, str) and x.startswith("[") and x.endswith("]")).all():
41
  df[col] = df[col].apply(json.loads)
42
  except Exception:
43
  pass
44
+
45
+ # Boolean string to actual bool
46
+ if df[col].dropna().isin(["TRUE", "FALSE"]).all():
47
  df[col] = df[col].map({"TRUE": True, "FALSE": False})
48
+
 
 
49
  return df
50
 
51
  def handle_missing_data(df: pd.DataFrame) -> pd.DataFrame: