complexifier 0.2.2__py3-none-any.whl → 0.3.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.
complexifier/__init__.py CHANGED
@@ -1 +1 @@
1
- from .main import *
1
+ from .main import *
complexifier/main.py CHANGED
@@ -19,19 +19,19 @@ def create_spag_error(word: str) -> str:
19
19
  weight = random.randint(1, 100)
20
20
  match weight:
21
21
  case 1:
22
- return error_object.missing_char()
22
+ return error_object.missing_char().result
23
23
  case 2:
24
- return error_object.char_swap()
24
+ return error_object.char_swap().result
25
25
  case 3:
26
- return error_object.extra_char()
26
+ return error_object.extra_char().result
27
27
  case 4:
28
- return error_object.nearby_char()
28
+ return error_object.nearby_char().result
29
29
  case 5:
30
- return error_object.similar_char()
30
+ return error_object.similar_char().result
31
31
  case 6:
32
- return error_object.random_space()
32
+ return error_object.random_space().result
33
33
  case 7:
34
- return error_object.repeated_char()
34
+ return error_object.repeated_char().result
35
35
  case 8:
36
36
  return word.lower()
37
37
  case 9:
@@ -54,6 +54,10 @@ def introduce_spag_error(df: pd.DataFrame, columns=None) -> pd.DataFrame:
54
54
  Returns:
55
55
  pd.DataFrame: The DataFrame with potential spelling errors introduced.
56
56
  """
57
+ if not isinstance(df, pd.DataFrame):
58
+ raise TypeError("Must be a pandas")
59
+ if df.empty:
60
+ return df
57
61
  if not columns:
58
62
  columns = df.select_dtypes(include=["string", "object"]).columns
59
63
  elif isinstance(columns, str):
@@ -80,6 +84,10 @@ def add_or_subtract_outliers(df: pd.DataFrame, columns=None) -> pd.DataFrame:
80
84
  Returns:
81
85
  pd.DataFrame: The DataFrame with outliers added.
82
86
  """
87
+ if not isinstance(df, pd.DataFrame):
88
+ raise TypeError("Must be a pandas")
89
+ if df.empty:
90
+ return df
83
91
  if not columns:
84
92
  columns = df.select_dtypes(include="number").columns
85
93
  elif isinstance(columns, str):
@@ -91,7 +99,7 @@ def add_or_subtract_outliers(df: pd.DataFrame, columns=None) -> pd.DataFrame:
91
99
  columns = [columns]
92
100
  elif not isinstance(columns, list):
93
101
  raise TypeError(f"Columns is type {type(columns)} but expected str or list")
94
-
102
+
95
103
  for col in columns:
96
104
  if col not in df.columns:
97
105
  raise ValueError(f"{col} is not a column.")
@@ -119,6 +127,10 @@ def add_standard_deviations(
119
127
  Returns:
120
128
  pd.DataFrame: The DataFrame with deviations added.
121
129
  """
130
+ if not isinstance(df, pd.DataFrame):
131
+ raise TypeError("Must be a pandas")
132
+ if df.empty:
133
+ return df
122
134
  if not columns:
123
135
  columns = df.select_dtypes(include="number").columns
124
136
  elif isinstance(columns, str):
@@ -151,8 +163,12 @@ def duplicate_rows(df: pd.DataFrame, sample_size=None) -> pd.DataFrame:
151
163
  Returns:
152
164
  pd.DataFrame: The DataFrame with duplicate rows added.
153
165
  """
166
+ if not isinstance(df, pd.DataFrame):
167
+ raise TypeError("Must be a pandas")
168
+ if df.empty:
169
+ return df
154
170
  if not sample_size:
155
- sample_size = random.randint(len(df[col]) // 100, len(df[col]) // 10)
171
+ sample_size = random.randint(len(df) // 100, len(df) // 10)
156
172
  new_rows = df.sample(sample_size)
157
173
  return pd.concat([df, new_rows])
158
174
 
@@ -166,12 +182,18 @@ def add_nulls(
166
182
  Args:
167
183
  df (pd.DataFrame): The DataFrame to modify.
168
184
  columns (list or str, optional): Specific columns to add nulls to. Defaults to all columns if not specified.
169
- min_percent (int): Minimum percentage of null values to insert.
170
- max_percent (int): Maximum percentage of null values to insert.
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%
171
187
 
172
188
  Returns:
173
189
  pd.DataFrame: The DataFrame with null values inserted.
174
190
  """
191
+ if not isinstance(df, pd.DataFrame):
192
+ raise TypeError("Must be a pandas")
193
+ if df.empty:
194
+ return df
195
+ if columns == []:
196
+ columns = df.columns.to_list()
175
197
  if not columns:
176
198
  columns = df.columns
177
199
  elif isinstance(columns, str):
@@ -180,8 +202,75 @@ def add_nulls(
180
202
  raise TypeError(f"Columns is type {type(columns)} but expected str or list")
181
203
 
182
204
  for col in columns:
183
- indices_to_none = df.sample(
184
- len(df) * random.randint(min_percent, max_percent) // 100
185
- ).index
205
+ chosen_percent = random.randint(min_percent, max_percent) / 100
206
+ sample_size = round(len(df) * chosen_percent)
207
+ if sample_size == 0:
208
+ sample_size = 1
209
+ indices_to_none = df.sample(sample_size).index
186
210
  df.loc[indices_to_none, col] = None
187
211
  return df
212
+
213
+
214
+ def mess_it_up(
215
+ df: pd.DataFrame,
216
+ columns=None,
217
+ min_std=1,
218
+ max_std=5,
219
+ sample_size=None,
220
+ min_percent=1,
221
+ max_percent=10,
222
+ introduce_spag=True,
223
+ add_outliers=True,
224
+ add_std=True,
225
+ duplicate=True,
226
+ add_null=True,
227
+ ) -> pd.DataFrame:
228
+ """
229
+ Applies several functions to add outliers, spelling errors and null values
230
+
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
+
240
+ """
241
+ if not isinstance(df, pd.DataFrame):
242
+ raise TypeError("Must be a pandas")
243
+ if df.empty:
244
+ return df
245
+ if columns == []:
246
+ columns = df.columns.to_list()
247
+ if not columns:
248
+ columns = df.columns.to_list()
249
+ elif isinstance(columns, str):
250
+ columns = [columns]
251
+ elif not isinstance(columns, list):
252
+ raise TypeError(f"Columns is type {type(columns)} but expected str or list")
253
+
254
+ string_cols = df[columns].select_dtypes(include="string").columns.to_list()
255
+ numeric_cols = df[columns].select_dtypes(include="number").columns.to_list()
256
+ if string_cols:
257
+ df = introduce_spag_error(df, columns=string_cols)
258
+ if numeric_cols:
259
+ df = add_or_subtract_outliers(df, columns=numeric_cols)
260
+ df = add_standard_deviations(
261
+ df, columns=numeric_cols, min_std=min_std, max_std=max_std
262
+ )
263
+
264
+ df = duplicate_rows(df, sample_size)
265
+ df = add_nulls(df, columns, min_percent=min_percent, max_percent=max_percent)
266
+ return df
267
+
268
+
269
+ data = pd.DataFrame(
270
+ {
271
+ "Name": ["Alice", "Bob", "Charlie", "David", "Eva"],
272
+ "Age": [28, 34, 29, 42, 25],
273
+ "City": ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"],
274
+ "Salary": [70000, 80000, 72000, 95000, 67000],
275
+ }
276
+ )
complexifier/test_main.py CHANGED
@@ -1,11 +1,16 @@
1
1
  import pytest
2
+ from unittest.mock import patch
2
3
  import pandas as pd
3
- from .main import (create_spag_error,
4
- introduce_spag_error,
5
- add_or_subtract_outliers,
6
- add_standard_deviations,
7
- duplicate_rows,
8
- add_nulls)
4
+ from math import floor
5
+ from .main import (
6
+ create_spag_error,
7
+ introduce_spag_error,
8
+ add_or_subtract_outliers,
9
+ add_standard_deviations,
10
+ duplicate_rows,
11
+ add_nulls,
12
+ mess_it_up,
13
+ )
9
14
 
10
15
 
11
16
  @pytest.fixture
@@ -13,58 +18,266 @@ def sample_df():
13
18
  """
14
19
  A fixture for tests
15
20
  """
16
- return pd.DataFrame({
17
- 'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],
18
- 'Age': [28, 34, 29, 42, 25],
19
- 'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix'],
20
- 'Salary': [70000, 80000, 72000, 95000, 67000]
21
- })
21
+ return pd.DataFrame(
22
+ {
23
+ "Name": ["Alice", "Bob", "Charlie", "David", "Eva"],
24
+ "Age": [28, 34, 29, 42, 25],
25
+ "City": ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"],
26
+ "Salary": [70000, 80000, 72000, 95000, 67000],
27
+ }
28
+ )
22
29
 
23
30
 
24
- def test_create_spag_error():
31
+ @pytest.mark.parametrize("word", ["hello", "world", "testword"])
32
+ def test_create_spag_error(word):
25
33
  """
26
- Test that for a word with sufficient length, the function must return a string of same length
34
+ Tests that the word returned is still a string
27
35
  """
28
- word = "hello"
29
36
  error_word = create_spag_error(word)
30
37
  assert isinstance(error_word, str)
31
- assert len(error_word) == len(word)
32
38
 
33
- def test_introduce_spag_error(sample_df):
39
+
40
+ @pytest.mark.parametrize("column_name", ["Name", "City"])
41
+ def test_introduce_spag_error(sample_df, column_name):
34
42
  """
35
43
  Test that DataFrame columns contain the potential spelling errors
36
44
  """
37
- df_with_errors = introduce_spag_error(sample_df, columns='Name')
38
- assert 'Name' in df_with_errors.columns
39
- assert all([isinstance(name, str) for name in df_with_errors['Name'].values])
45
+ df_with_errors = introduce_spag_error(sample_df, columns=column_name)
46
+ assert column_name in df_with_errors.columns
47
+ assert all([isinstance(name, str) for name in df_with_errors[column_name].values])
48
+
40
49
 
41
- def test_add_or_subtract_outliers(sample_df):
50
+ @pytest.mark.parametrize("column_name", ["Salary"])
51
+ def test_add_or_subtract_outliers(sample_df, column_name):
42
52
  """
43
53
  Test that outliers are added to the numerical columns
44
54
  """
45
- df_with_outliers = add_or_subtract_outliers(sample_df, columns='Salary')
46
- assert 'Salary' in df_with_outliers.columns
47
- assert df_with_outliers['Salary'].dtype == float or df_with_outliers['Salary'].dtype == int
55
+ df_with_outliers = add_or_subtract_outliers(sample_df, columns=column_name)
56
+ assert column_name in df_with_outliers.columns
57
+ assert pd.api.types.is_numeric_dtype(df_with_outliers[column_name])
58
+
48
59
 
49
- def test_add_standard_deviations(sample_df):
50
- """
51
- Test that standard deviations are added to the Age column
60
+ @pytest.mark.parametrize("column_name", ["Age", "Salary"])
61
+ def test_add_standard_deviations(sample_df, column_name):
52
62
  """
53
- df_with_deviations = add_standard_deviations(sample_df, columns='Age')
54
- assert 'Age' in df_with_deviations.columns
55
- assert df_with_deviations['Age'].dtype == float or df_with_deviations['Age'].dtype == int
63
+ Test that standard deviations are added to the specified column
64
+ """
65
+ df_with_deviations = add_standard_deviations(sample_df, columns=column_name)
66
+ assert column_name in df_with_deviations.columns
67
+ assert pd.api.types.is_numeric_dtype(df_with_deviations[column_name])
68
+
56
69
 
57
- def test_duplicate_rows(sample_df):
70
+ @pytest.mark.parametrize("sample_size", [0, 2, 5])
71
+ def test_duplicate_rows(sample_df, sample_size):
58
72
  """
59
73
  Test that duplicate rows are added
60
74
  """
61
- df_with_duplicates = duplicate_rows(sample_df, sample_size=2)
62
- assert len(df_with_duplicates) == len(sample_df) + 2
75
+ df_with_duplicates = duplicate_rows(sample_df, sample_size=sample_size)
76
+ assert len(df_with_duplicates) == len(sample_df) + sample_size
63
77
 
64
- def test_add_nulls(sample_df):
78
+
79
+ @pytest.mark.parametrize(
80
+ "column_name,min_percent,max_percent", [("City", 10, 20), ("Name", 20, 30)]
81
+ )
82
+ def test_add_nulls(sample_df, column_name, min_percent, max_percent):
65
83
  """
66
84
  Test that nulls are added to the DataFrame
67
85
  """
68
- df_with_nulls = add_nulls(sample_df, columns='City', min_percent=20, max_percent=30)
69
- assert 'City' in df_with_nulls.columns
70
- assert df_with_nulls['City'].isnull().sum() > 0
86
+ df_with_nulls = add_nulls(
87
+ sample_df, columns=column_name, min_percent=min_percent, max_percent=max_percent
88
+ )
89
+ assert column_name in df_with_nulls.columns
90
+ null_count = df_with_nulls[column_name].isnull().sum()
91
+ print(df_with_nulls)
92
+ assert float(null_count) >= 0.0
93
+ assert (
94
+ (min_percent * 0.01 * len(sample_df))
95
+ <= null_count
96
+ <= round(max_percent * 0.01 * len(sample_df))
97
+ )
98
+
99
+
100
+ def test_mess_it_up(sample_df):
101
+ """
102
+ Tests the mess_it_up_function
103
+ """
104
+ df_messed_up = mess_it_up(
105
+ sample_df,
106
+ columns=["Name", "Age", "City", "Salary"],
107
+ min_std=1,
108
+ max_std=2,
109
+ sample_size=2,
110
+ min_percent=10,
111
+ max_percent=20,
112
+ )
113
+
114
+ # Check that the specified number of duplicate rows has been added
115
+ assert (
116
+ len(df_messed_up) == len(sample_df) + 2
117
+ ), "Unexpected number of duplicate rows"
118
+
119
+ # Check for potential null values
120
+ for col in ["Name", "Age", "City", "Salary"]:
121
+ null_count = df_messed_up[col].isnull().sum()
122
+ assert null_count > 0, f"No nulls introduced in {col} column"
123
+
124
+
125
+ @pytest.mark.parametrize(
126
+ "columns,min_std,max_std,sample_size,min_percent,max_percent",
127
+ [
128
+ (["Name", "Age"], 1, 2, 2, 10, 20),
129
+ (["City", "Salary"], 2, 4, 3, 15, 25),
130
+ (["Name", "City", "Age"], 1, 3, 1, 5, 10),
131
+ ],
132
+ )
133
+ def test_parameterised_mess_it_up(
134
+ sample_df, columns, min_std, max_std, sample_size, min_percent, max_percent
135
+ ):
136
+ """
137
+ Tests the mess_it_up function with different configurations
138
+ """
139
+ df_messed_up = mess_it_up(
140
+ sample_df,
141
+ columns=columns,
142
+ min_std=min_std,
143
+ max_std=max_std,
144
+ sample_size=sample_size,
145
+ min_percent=min_percent,
146
+ max_percent=max_percent,
147
+ )
148
+
149
+ # Check that the specified number of duplicate rows has been added
150
+ assert (
151
+ len(df_messed_up) == len(sample_df) + sample_size
152
+ ), "Unexpected number of duplicate rows"
153
+
154
+ # Check for potential null values
155
+ for col in columns:
156
+ null_count = df_messed_up[col].isnull().sum()
157
+ assert null_count > 0, f"No nulls introduced in {col} column"
158
+
159
+
160
+ def test_empty_dataframe_introduce_spag_error():
161
+ """
162
+ Test introduce_spag_error with an empty DataFrame
163
+ """
164
+ empty_df = pd.DataFrame(columns=["Name"])
165
+ df_spag = introduce_spag_error(empty_df, columns="Name")
166
+ assert df_spag.empty
167
+
168
+
169
+ def test_empty_dataframe_add_or_subtract_outliers():
170
+ """
171
+ Test add_or_subtract_outliers with an empty DataFrame
172
+ """
173
+ empty_df = pd.DataFrame(columns=["Salary"])
174
+ df_outliers = add_or_subtract_outliers(empty_df, columns="Salary")
175
+ assert df_outliers.empty
176
+
177
+
178
+ def test_empty_dataframe_add_standard_deviations():
179
+ """
180
+ Test add_standard_deviations with an empty DataFrame
181
+ """
182
+ empty_df = pd.DataFrame(columns=["Age"])
183
+ df_deviations = add_standard_deviations(empty_df, columns="Age")
184
+ assert df_deviations.empty
185
+
186
+
187
+ def test_empty_dataframe_duplicate_rows():
188
+ """
189
+ Test duplicate_rows with an empty DataFrame
190
+ """
191
+ empty_df = pd.DataFrame(columns=["Name", "Age"])
192
+ df_duplicates = duplicate_rows(empty_df, sample_size=2)
193
+ assert df_duplicates.empty
194
+
195
+
196
+ def test_empty_dataframe_add_nulls():
197
+ """
198
+ Test add_nulls with an empty DataFrame
199
+ """
200
+ empty_df = pd.DataFrame(columns=["City"])
201
+ df_nulls = add_nulls(empty_df, columns="City", min_percent=10, max_percent=20)
202
+ assert df_nulls.empty
203
+
204
+
205
+ def test_empty_dataframe_mess_it_up():
206
+ """
207
+ Test mess_it_up with an empty DataFrame
208
+ """
209
+ empty_df = pd.DataFrame(columns=["Name", "Age", "City", "Salary"])
210
+ df_messed = mess_it_up(empty_df, columns=["Name", "Age", "City", "Salary"])
211
+ assert df_messed.empty
212
+
213
+
214
+ def test_nonexistent_column_introduce_spag_error(sample_df):
215
+ """
216
+ Test introduce_spag_error with a nonexistent column
217
+ """
218
+ with pytest.raises(ValueError):
219
+ introduce_spag_error(sample_df, columns="Nonexistent")
220
+
221
+
222
+ def test_nonexistent_column_add_or_subtract_outliers(sample_df):
223
+ """
224
+ Test add_or_subtract_outliers with a nonexistent column
225
+ """
226
+ with pytest.raises(ValueError):
227
+ add_or_subtract_outliers(sample_df, columns="Nonexistent")
228
+
229
+
230
+ def test_nonexistent_column_add_standard_deviations(sample_df):
231
+ """
232
+ Test add_standard_deviations with a nonexistent column
233
+ """
234
+ with pytest.raises(ValueError):
235
+ add_standard_deviations(sample_df, columns="Nonexistent")
236
+
237
+
238
+ def test_mixed_data_types_introduce_spag_error():
239
+ """
240
+ Test introduce_spag_error with mixed data types
241
+ """
242
+ mixed_df = pd.DataFrame(
243
+ {
244
+ "String": ["A", "B", "C"],
245
+ "Integer": [1, 2, 3],
246
+ "Float": [0.1, 0.2, 0.3],
247
+ "DateTime": pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-03"]),
248
+ }
249
+ )
250
+ df_spag = introduce_spag_error(mixed_df, columns="String")
251
+ assert "String" in df_spag.columns
252
+
253
+
254
+ def test_mixed_data_types_add_or_subtract_outliers():
255
+ """
256
+ Test add_or_subtract_outliers with mixed data types
257
+ """
258
+ mixed_df = pd.DataFrame(
259
+ {
260
+ "String": ["A", "B", "C"],
261
+ "Integer": [1, 2, 3],
262
+ "Float": [0.1, 0.2, 0.3],
263
+ "DateTime": pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-03"]),
264
+ }
265
+ )
266
+ df_outliers = add_or_subtract_outliers(mixed_df, columns="Integer")
267
+ assert "Integer" in df_outliers.columns
268
+
269
+
270
+ def test_mixed_data_types_add_standard_deviations():
271
+ """
272
+ Test add_standard_deviations with mixed data types
273
+ """
274
+ mixed_df = pd.DataFrame(
275
+ {
276
+ "String": ["A", "B", "C"],
277
+ "Integer": [1, 2, 3],
278
+ "Float": [0.1, 0.2, 0.3],
279
+ "DateTime": pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-03"]),
280
+ }
281
+ )
282
+ df_deviations = add_standard_deviations(mixed_df, columns="Float")
283
+ assert "Float" in df_deviations.columns
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: complexifier
3
- Version: 0.2.2
3
+ Version: 0.3.0
4
4
  Summary: A library to make data worse
5
5
  Project-URL: Homepage, https://github.com/ruyzambrano/complexifier
6
6
  Project-URL: Issues, https://github.com/ruyzambrano/complexifier/issues
@@ -0,0 +1,7 @@
1
+ complexifier/__init__.py,sha256=8D5a8oKgqd6WA1RUkiKCn4l_PVemtyuckxQut0vDHXM,20
2
+ complexifier/main.py,sha256=tR85qn853uPwA9_hzOg7D6MRLpf_vWePGWEzBLqhY8I,9664
3
+ complexifier/test_main.py,sha256=7mhywpJXtU59M9oh0bUXLIVup2qXqW_awi2J9FpCCHo,8595
4
+ complexifier-0.3.0.dist-info/METADATA,sha256=REQbOvWLaLR9t44Ex6KMWsG2cDuEppy5COad2QvmJAc,2986
5
+ complexifier-0.3.0.dist-info/WHEEL,sha256=C2FUgwZgiLbznR-k0b_5k3Ai_1aASOXDss3lzCUsUug,87
6
+ complexifier-0.3.0.dist-info/licenses/LICENSE,sha256=2bm9uFabQZ3Ykb_SaSU_uUbAj2-htc6WJQmS_65qD00,1073
7
+ complexifier-0.3.0.dist-info/RECORD,,
@@ -1,7 +0,0 @@
1
- complexifier/__init__.py,sha256=zDr350exO14Ii8Pj3TXwPuRxIDrEjrg43CpjYABDqh4,19
2
- complexifier/main.py,sha256=bi8XYFpfh05TgYDefBFz8Y5vFl0-Wx-dcuZBOAEJdyY,6551
3
- complexifier/test_main.py,sha256=nDg03HGhi_QMox_GAkonkakgOcXDBsuro6AR5mbpyWw,2391
4
- complexifier-0.2.2.dist-info/METADATA,sha256=yrdaeptIdP7SAOERGhVtgta9xLHIydiOg9Ucys3KeN4,2986
5
- complexifier-0.2.2.dist-info/WHEEL,sha256=C2FUgwZgiLbznR-k0b_5k3Ai_1aASOXDss3lzCUsUug,87
6
- complexifier-0.2.2.dist-info/licenses/LICENSE,sha256=2bm9uFabQZ3Ykb_SaSU_uUbAj2-htc6WJQmS_65qD00,1073
7
- complexifier-0.2.2.dist-info/RECORD,,