complexifier 0.3.2__py3-none-any.whl → 0.3.4__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.
complexifier/__init__.py CHANGED
@@ -1 +1,11 @@
1
- from .main import *
1
+ from .main import (
2
+ add_nulls,
3
+ add_or_subtract_outliers,
4
+ add_sequential_anomaly,
5
+ add_standard_deviations,
6
+ create_spag_error,
7
+ introduce_spag_error,
8
+ mess_it_up,
9
+ duplicate_rows,
10
+ swap_dates,
11
+ )
@@ -0,0 +1,4 @@
1
+ import sys
2
+ import os
3
+
4
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
complexifier/main.py CHANGED
@@ -1,58 +1,57 @@
1
1
  import random
2
-
3
2
  from typo import StrErrer
4
3
  import pandas as pd
5
4
 
6
5
 
7
6
  def create_spag_error(word: str) -> str:
8
- """Gives a 10% chance to introduce a spelling error to a word.
9
-
10
- Args:
11
- word (str): The original word to potentially alter.
7
+ """
8
+ Gives a 10% chance to introduce a spelling error to a word.
12
9
 
13
- Returns:
14
- str: The original word or a word with a random spelling error.
10
+ :param word: The original word to potentially alter.
11
+ :type word: str
12
+ :return: The original word or a word with a random spelling error.
13
+ :rtype: str
15
14
  """
16
15
  if len(word) < 3:
17
16
  return word
18
17
  error_object = StrErrer(word)
19
18
  weight = random.randint(1, 100)
20
- match weight:
21
- case 1:
22
- return error_object.missing_char().result
23
- case 2:
24
- return error_object.char_swap().result
25
- case 3:
26
- return error_object.extra_char().result
27
- case 4:
28
- return error_object.nearby_char().result
29
- case 5:
30
- return error_object.similar_char().result
31
- case 6:
32
- return error_object.random_space().result
33
- case 7:
34
- return error_object.repeated_char().result
35
- case 8:
36
- return word.lower()
37
- case 9:
38
- return word.upper()
39
- case 10:
40
- return "".join(
41
- [char.upper() if random.randint(0, 100) < 10 else char for char in word]
42
- )
43
- case _:
44
- return word
19
+ if weight == 1:
20
+ return error_object.missing_char().result
21
+ elif weight == 2:
22
+ return error_object.char_swap().result
23
+ elif weight == 3:
24
+ return error_object.extra_char().result
25
+ elif weight == 4:
26
+ return error_object.nearby_char().result
27
+ elif weight == 5:
28
+ return error_object.similar_char().result
29
+ elif weight == 6:
30
+ return error_object.random_space().result
31
+ elif weight == 7:
32
+ return error_object.repeated_char().result
33
+ elif weight == 8:
34
+ return word.lower()
35
+ elif weight == 9:
36
+ return word.upper()
37
+ elif weight == 10:
38
+ return "".join(
39
+ [char.upper() if random.randint(0, 100) < 10 else char for char in word]
40
+ )
41
+ else:
42
+ return word
45
43
 
46
44
 
47
45
  def introduce_spag_error(df: pd.DataFrame, columns=None) -> pd.DataFrame:
48
- """Applies random spelling errors to specified columns in a DataFrame.
49
-
50
- Args:
51
- df (pd.DataFrame): The DataFrame to alter.
52
- columns (list or str): Column names to apply errors to. Defaults to all string columns.
53
-
54
- Returns:
55
- pd.DataFrame: The DataFrame with potential spelling errors introduced.
46
+ """
47
+ Applies random spelling errors to specified columns in a DataFrame.
48
+
49
+ :param df: The DataFrame to alter.
50
+ :type df: pd.DataFrame
51
+ :param columns: Column names to apply errors to. Defaults to all string columns.
52
+ :type columns: list or str, optional
53
+ :return: The DataFrame with potential spelling errors introduced.
54
+ :rtype: pd.DataFrame
56
55
  """
57
56
  if not isinstance(df, pd.DataFrame):
58
57
  raise TypeError("Must be a pandas")
@@ -75,14 +74,15 @@ def introduce_spag_error(df: pd.DataFrame, columns=None) -> pd.DataFrame:
75
74
 
76
75
 
77
76
  def add_or_subtract_outliers(df: pd.DataFrame, columns=None) -> pd.DataFrame:
78
- """Adds or subtracts a random integer in columns of between 1% and 10% of the rows.
79
-
80
- Args:
81
- df (pd.DataFrame): The DataFrame to modify.
82
- columns (list or str): Column names to adjust. Defaults to all numeric columns if not specified.
83
-
84
- Returns:
85
- pd.DataFrame: The DataFrame with outliers added.
77
+ """
78
+ Adds or subtracts a random integer in columns of between 1% and 10% of the rows.
79
+
80
+ :param df: The DataFrame to modify.
81
+ :type df: pd.DataFrame
82
+ :param columns: Column names to adjust. Defaults to all numeric columns if not specified.
83
+ :type columns: list or str, optional
84
+ :return: The DataFrame with outliers added.
85
+ :rtype: pd.DataFrame
86
86
  """
87
87
  if not isinstance(df, pd.DataFrame):
88
88
  raise TypeError("Must be a pandas")
@@ -95,11 +95,6 @@ def add_or_subtract_outliers(df: pd.DataFrame, columns=None) -> pd.DataFrame:
95
95
  elif not isinstance(columns, list):
96
96
  raise TypeError(f"Columns is type {type(columns)} but expected str or list")
97
97
 
98
- elif isinstance(columns, str):
99
- columns = [columns]
100
- elif not isinstance(columns, list):
101
- raise TypeError(f"Columns is type {type(columns)} but expected str or list")
102
-
103
98
  for col in columns:
104
99
  if col not in df.columns:
105
100
  raise ValueError(f"{col} is not a column.")
@@ -116,16 +111,19 @@ def add_or_subtract_outliers(df: pd.DataFrame, columns=None) -> pd.DataFrame:
116
111
  def add_standard_deviations(
117
112
  df: pd.DataFrame, columns=None, min_std=1, max_std=5
118
113
  ) -> pd.DataFrame:
119
- """Adds random deviations to entries in specified numeric columns to simulate data anomalies.
120
-
121
- Args:
122
- df (pd.DataFrame): The DataFrame to manipulate.
123
- columns (list or str): Column names to modify. Defaults to numeric columns if not specified.
124
- min_std (int): Minimum number of standard deviations to add. Defaults to 1
125
- max_std (int): Maximum number of standard deviations to add. Defaults to 5
126
-
127
- Returns:
128
- pd.DataFrame: The DataFrame with deviations added.
114
+ """
115
+ Adds random deviations to entries in specified numeric columns to simulate data anomalies.
116
+
117
+ :param df: The DataFrame to manipulate.
118
+ :type df: pd.DataFrame
119
+ :param columns: Column names to modify. Defaults to numeric columns if not specified.
120
+ :type columns: list or str, optional
121
+ :param min_std: Minimum number of standard deviations to add. Defaults to 1
122
+ :type min_std: int, optional
123
+ :param max_std: Maximum number of standard deviations to add. Defaults to 5
124
+ :type max_std: int, optional
125
+ :return: The DataFrame with deviations added.
126
+ :rtype: pd.DataFrame
129
127
  """
130
128
  if not isinstance(df, pd.DataFrame):
131
129
  raise TypeError("Must be a pandas")
@@ -141,27 +139,32 @@ def add_standard_deviations(
141
139
  for col in columns:
142
140
  if col not in df.columns:
143
141
  raise ValueError(f"{col} is not a column.")
142
+
143
+ # Ensure the column can hold float values before modifying it
144
+ df[col] = df[col].astype(float)
145
+
144
146
  sample_size = random.randint(len(df[col]) // 100, len(df[col]) // 10)
145
147
  standard_deviation = df[col].std()
146
148
  random_indices = df.sample(sample_size).index
147
149
  df.loc[random_indices, col] = df.loc[random_indices, col].apply(
148
150
  lambda row: row
149
151
  + random.randint(min_std, max_std)
150
- * standard_deviation
151
- * random.choice([1, -1])
152
+ - standard_deviation
153
+ - random.choice([1, -1])
152
154
  )
153
155
  return df
154
156
 
155
157
 
156
158
  def duplicate_rows(df: pd.DataFrame, sample_size=None) -> pd.DataFrame:
157
- """Adds duplicate rows to a DataFrame.
158
-
159
- Args:
160
- df (pd.DataFrame): DataFrame to which duplicates will be added.
161
- sample_size (int): number of rows to duplicate. A random percentage between 1% and 10% if not specified.
162
-
163
- Returns:
164
- pd.DataFrame: The DataFrame with duplicate rows added.
159
+ """
160
+ Adds duplicate rows to a DataFrame.
161
+
162
+ :param df: DataFrame to which duplicates will be added.
163
+ :type df: pd.DataFrame
164
+ :param sample_size: Number of rows to duplicate. A random percentage between 1% and 10% if not specified.
165
+ :type sample_size: int, optional
166
+ :return: The DataFrame with duplicate rows added.
167
+ :rtype: pd.DataFrame
165
168
  """
166
169
  if not isinstance(df, pd.DataFrame):
167
170
  raise TypeError("Must be a pandas")
@@ -179,14 +182,16 @@ def add_nulls(
179
182
  """
180
183
  Inserts null values into specified DataFrame columns.
181
184
 
182
- Args:
183
- df (pd.DataFrame): The DataFrame to modify.
184
- columns (list or str, optional): Specific columns to add nulls to. Defaults to all columns if not specified.
185
- min_percent (int): Minimum percentage of null values to insert. Defaults to 1%
186
- max_percent (int): Maximum percentage of null values to insert. Defaults to 10%
187
-
188
- Returns:
189
- pd.DataFrame: The DataFrame with null values inserted.
185
+ :param df: The DataFrame to modify.
186
+ :type df: pd.DataFrame
187
+ :param columns: Specific columns to add nulls to. Defaults to all columns if not specified.
188
+ :type columns: list or str, optional
189
+ :param min_percent: Minimum percentage of null values to insert. Defaults to 1%
190
+ :type min_percent: int, optional
191
+ :param max_percent: Maximum percentage of null values to insert. Defaults to 10%
192
+ :type max_percent: int, optional
193
+ :return: The DataFrame with null values inserted.
194
+ :rtype: pd.DataFrame
190
195
  """
191
196
  if not isinstance(df, pd.DataFrame):
192
197
  raise TypeError("Must be a pandas")
@@ -211,6 +216,115 @@ def add_nulls(
211
216
  return df
212
217
 
213
218
 
219
+ def swap_dates(df: pd.DataFrame, columns=None, sample_size: int = None) -> pd.DataFrame:
220
+ """
221
+ Introduces date errors by swapping month and day positions in datetime columns.
222
+
223
+ Randomly selects sample_size rows, then swaps the month and day for those
224
+ where the day value is <= 12 (e.g., 2024-01-03 becomes 2024-03-01).
225
+
226
+ :param df: The DataFrame to modify.
227
+ :type df: pd.DataFrame
228
+ :param columns: Column names to apply date swaps to. Defaults to all datetime columns.
229
+ :type columns: list or str, optional
230
+ :param sample_size: Number of rows to randomly select for potential swapping. Defaults to a random number between 1% and 10% of rows.
231
+ :type sample_size: int, optional
232
+ :return: The DataFrame with swapped dates.
233
+ :rtype: pd.DataFrame
234
+ """
235
+ if not isinstance(df, pd.DataFrame):
236
+ raise TypeError("Must be a pandas")
237
+ if df.empty:
238
+ return df
239
+ if not columns:
240
+ columns = df.select_dtypes(include=["datetime", "datetime64", "datetimetz"]).columns.to_list()
241
+ elif isinstance(columns, str):
242
+ columns = [columns]
243
+ elif not isinstance(columns, list):
244
+ raise TypeError(f"Columns is type {type(columns)} but expected str or list")
245
+
246
+ for col in columns:
247
+ if col not in df.columns:
248
+ raise ValueError(f"{col} not in DataFrame")
249
+ if not pd.api.types.is_datetime64_any_dtype(df[col]):
250
+ raise TypeError(f"{col} is {df[col].dtype}, not a datetime type")
251
+
252
+ if sample_size is None:
253
+ sample_size = random.randint(len(df) // 100, len(df) // 10)
254
+
255
+ selected_indices = df.sample(min(sample_size, len(df))).index
256
+
257
+ for col in columns:
258
+ for idx in selected_indices:
259
+ dt = df.loc[idx, col]
260
+ if pd.isna(dt):
261
+ continue
262
+ if dt.day <= 12:
263
+ try:
264
+ df.loc[idx, col] = dt.replace(month=dt.day, day=dt.month)
265
+ except ValueError:
266
+ pass
267
+ return df
268
+
269
+
270
+ def add_sequential_anomaly(
271
+ df: pd.DataFrame, sequence_size: int = 10, magnitude: int = 3,
272
+ columns=None, direction: str = "positive"
273
+ ) -> pd.DataFrame:
274
+ """
275
+ Introduces a sequential anomaly into the DataFrame by uniformly adjusting
276
+ a series of consecutive data points in numeric columns.
277
+
278
+ The adjustment is calculated as the column's standard deviation multiplied
279
+ by the magnitude, added or subtracted based on the direction parameter.
280
+
281
+ :param df: The DataFrame to modify.
282
+ :type df: pd.DataFrame
283
+ :param sequence_size: Number of consecutive data points to adjust. Capped at 10% of DataFrame length. Defaults to 10.
284
+ :type sequence_size: int, optional
285
+ :param magnitude: Number of standard deviations to adjust by. Defaults to 3.
286
+ :type magnitude: int, optional
287
+ :param columns: Column names to modify. Defaults to all numeric columns if not specified.
288
+ :type columns: list or str, optional
289
+ :param direction: Whether the sequence is adjusted up ('positive') or down ('negative'). Defaults to 'positive'.
290
+ :type direction: str, optional
291
+ :return: The DataFrame with sequential anomaly introduced.
292
+ :rtype: pd.DataFrame
293
+ """
294
+ if not isinstance(df, pd.DataFrame):
295
+ raise TypeError("Must be a pandas")
296
+ if df.empty:
297
+ return df
298
+ if direction not in ("positive", "negative"):
299
+ raise ValueError("direction must be 'positive' or 'negative'")
300
+ if not columns:
301
+ columns = df.select_dtypes(include="number").columns.to_list()
302
+ elif isinstance(columns, str):
303
+ columns = [columns]
304
+ elif not isinstance(columns, list):
305
+ raise TypeError(f"Columns is type {type(columns)} but expected str or list")
306
+
307
+ for col in columns:
308
+ if col not in df.columns:
309
+ raise ValueError(f"{col} is not a column.")
310
+
311
+ max_sequence = max(1, len(df) // 10)
312
+ sequence_size = min(sequence_size, max_sequence)
313
+
314
+ start_idx = random.randint(0, len(df) - sequence_size)
315
+
316
+ for col in columns:
317
+ if pd.api.types.is_integer_dtype(df[col]):
318
+ df[col] = df[col].astype(float)
319
+ std = df[col].std()
320
+ adjustment = std * magnitude
321
+ if direction == "negative":
322
+ adjustment = -adjustment
323
+ df.iloc[start_idx:start_idx + sequence_size, df.columns.get_loc(col)] += adjustment
324
+
325
+ return df
326
+
327
+
214
328
  def mess_it_up(
215
329
  df: pd.DataFrame,
216
330
  columns=None,
@@ -223,25 +337,52 @@ def mess_it_up(
223
337
  add_outliers=True,
224
338
  add_std=True,
225
339
  duplicate=True,
226
- add_null=True
340
+ add_null=True,
341
+ swap_date=True,
342
+ sequential_anomaly=True,
343
+ sequence_size=10,
344
+ magnitude=3,
345
+ direction="positive",
227
346
  ) -> pd.DataFrame:
228
347
  """
229
348
  Applies several functions to add outliers, spelling errors and null values
230
349
 
231
- Args:
232
- df (pd.DataFrame): The DataFrame to modify.
233
- columns (list or str, optional): Specific columns to add nulls to. Defaults to all columns if not specified.
234
- min_std (int): Minimum number of standard deviations to add. Defaults to 1
235
- max_std (int): Maximum number of standard deviations to add. Defaults to 5
236
- sample_size (int, optional): Number of rows to duplicate. Randomly selected if not specified.
237
- min_percent (int): Minimum percentage of null values to insert. Defaults to 1%
238
- max_percent (int): Maximum percentage of null values to insert. Defaults to 10%
239
- introduce_spag (bool): Adds spelling and grammar errors into string data. Defaults to True
240
- add_outliers (bool): Adds outliers to numerical data. Defaults to True
241
- add_std (bool): Adds standard deviations to the data. Defaults to True
242
- duplicate (bool): Adds duplicate rows to the data. Defaults to True
243
- add_null (bool): Adds null values to the dataset. Defaults to True
244
-
350
+ :param df: The DataFrame to modify.
351
+ :type df: pd.DataFrame
352
+ :param columns: Specific columns to modify. Defaults to all columns if not specified.
353
+ :type columns: list or str, optional
354
+ :param min_std: Minimum number of standard deviations to add. Defaults to 1
355
+ :type min_std: int, optional
356
+ :param max_std: Maximum number of standard deviations to add. Defaults to 5
357
+ :type max_std: int, optional
358
+ :param sample_size: Number of rows to duplicate. Randomly selected if not specified.
359
+ :type sample_size: int, optional
360
+ :param min_percent: Minimum percentage of null values to insert. Defaults to 1%
361
+ :type min_percent: int, optional
362
+ :param max_percent: Maximum percentage of null values to insert. Defaults to 10%
363
+ :type max_percent: int, optional
364
+ :param introduce_spag: Adds spelling and grammar errors into string data. Defaults to True
365
+ :type introduce_spag: bool, optional
366
+ :param add_outliers: Adds outliers to numerical data. Defaults to True
367
+ :type add_outliers: bool, optional
368
+ :param add_std: Adds standard deviations to the data. Defaults to True
369
+ :type add_std: bool, optional
370
+ :param duplicate: Adds duplicate rows to the data. Defaults to True
371
+ :type duplicate: bool, optional
372
+ :param add_null: Adds null values to the dataset. Defaults to True
373
+ :type add_null: bool, optional
374
+ :param swap_date: Swaps month and day in datetime columns. Defaults to True
375
+ :type swap_date: bool, optional
376
+ :param sequential_anomaly: Adds a sequential anomaly to numeric columns. Defaults to True
377
+ :type sequential_anomaly: bool, optional
378
+ :param sequence_size: Number of consecutive data points for sequential anomaly. Defaults to 10.
379
+ :type sequence_size: int, optional
380
+ :param magnitude: Number of standard deviations for sequential anomaly. Defaults to 3.
381
+ :type magnitude: int, optional
382
+ :param direction: Direction of sequential anomaly adjustment ('positive' or 'negative'). Defaults to 'positive'.
383
+ :type direction: str, optional
384
+ :return: The modified DataFrame.
385
+ :rtype: pd.DataFrame
245
386
  """
246
387
  if not isinstance(df, pd.DataFrame):
247
388
  raise TypeError("Must be a pandas")
@@ -258,6 +399,7 @@ def mess_it_up(
258
399
 
259
400
  string_cols = df[columns].select_dtypes(include="string").columns.to_list()
260
401
  numeric_cols = df[columns].select_dtypes(include="number").columns.to_list()
402
+ datetime_cols = df[columns].select_dtypes(include=["datetime", "datetime64", "datetimetz"]).columns.to_list()
261
403
  if string_cols:
262
404
  if introduce_spag:
263
405
  df = introduce_spag_error(df, string_cols)
@@ -265,21 +407,14 @@ def mess_it_up(
265
407
  if add_outliers:
266
408
  df = add_or_subtract_outliers(df, numeric_cols)
267
409
  if add_std:
268
- df = add_standard_deviations(
269
- df, numeric_cols, min_std, max_std
270
- )
410
+ df = add_standard_deviations(df, numeric_cols, min_std, max_std)
411
+ if sequential_anomaly:
412
+ df = add_sequential_anomaly(df, sequence_size, magnitude, numeric_cols, direction)
413
+ if datetime_cols:
414
+ if swap_date:
415
+ df = swap_dates(df, datetime_cols)
271
416
  if duplicate:
272
417
  df = duplicate_rows(df, sample_size)
273
418
  if add_null:
274
419
  df = add_nulls(df, columns, min_percent, max_percent)
275
420
  return df
276
-
277
-
278
- data = pd.DataFrame(
279
- {
280
- "Name": ["Alice", "Bob", "Charlie", "David", "Eva"],
281
- "Age": [28, 34, 29, 42, 25],
282
- "City": ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"],
283
- "Salary": [70000, 80000, 72000, 95000, 67000],
284
- }
285
- )