-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
551 lines (384 loc) · 13.4 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
import pathlib
import numpy as np
import pandas as pd
from rapidfuzz import fuzz
from recordlinkage.base import BaseCompareFeature
from recordlinkage.utils import fillna as _fillna
import geopandas as gpd
import json
from inspect import signature
from scipy import spatial
from unidecode import unidecode
def clean_address_data(
df: pd.DataFrame,
field_to_clean: str,
standardisation_file: str,
min_length: int,
suffix: str,
convert_non_ascii: bool = False,
) -> tuple[pd.DataFrame, str]:
"""Cleans `field_to_clean` returns `pd.DataFrame` with added `pd.Series` containing cleaned data, and name of cleaned field.
Applies regex pattern replacements from file
Strips leading and trailing spaces
Converts to uppercase
Parameters
----------
df: `pd.DataFrame`
`pd.DataFrame` of data including a field to be cleaned
field_to_clean: str
Name of `pd.Series` in `df` that will be cleaned
min_length: int
Minimum number of characters that `field_to_clean` must contain otherwise class as NaN
suffix: str
Suffix to add to `field_to_clean` to distinguish cleaned field from original field in dataframe.
convert_non_ascii: bool
Whether to convert non ascii characters in `field_to_clean` or not. See Documentation re. non ascii characters in GB1900.
Returns
-------
df: `pd.DataFrame`
`pd.DataFrame` containing original data with added `pd.Series` containing cleaned data
field_to_clean_new: str
Name of `pd.Series` in `df` that contains cleaned data.
"""
field_to_clean_new = f"{field_to_clean}{suffix}"
df[field_to_clean_new] = df[field_to_clean]
if convert_non_ascii is True:
df[field_to_clean_new] = df[field_to_clean_new].apply(
lambda a: a if pd.isna(a) else unidecode(a)
)
df[field_to_clean_new] = df[field_to_clean_new].str.upper()
if standardisation_file is not None:
with open(standardisation_file) as f:
street_standardisation = json.load(f)
for patt, repla in street_standardisation.items():
df[field_to_clean_new] = df[field_to_clean_new].replace(
patt, repla, regex=True
)
df = df.fillna(value=np.nan)
df[field_to_clean_new] = df[field_to_clean_new].str.strip()
if min_length is not None:
df[field_to_clean_new] = np.where(
df[field_to_clean_new].str.len() >= min_length,
df[field_to_clean_new],
np.nan,
)
return (df, field_to_clean_new)
def process_coords(
target_df: pd.DataFrame,
long_field: str,
lat_field: str,
projection: str,
):
"""Processes coordindates in a `pd.DataFrame` reading them into a geometry field in a `gpd.GeoDatFrame`.
Returns a gpd.GeoDataFrame with geometry data and specified crs.
Parameters
----------
target_df: `pd.DataFrame`
`pd.DataFrame` containing coordinates but not read into geometry field of a `gpd.GeoDataFrame`.
long_field: str
Name of `pd.Series` containing longitude values.
lat_field: str
Name of `pd.Series` containing latitude values.
projection: str
Intended CRS projection.
Returns
-------
target_gdf: `gpd.GeoDataFrame`
`gpd.GeoDataFrame` containing original data (minus the original lat and long fields) with geometry column in WKT.
"""
target_gdf = gpd.GeoDataFrame(
target_df,
geometry=gpd.points_from_xy(
target_df[long_field],
target_df[lat_field],
),
crs=projection,
).drop(
columns=[
long_field,
lat_field,
]
)
return target_gdf
class rapidfuzzy_wratio_comparer(BaseCompareFeature):
"""Provides funtionality for recordlinkage BaseCompareFeature to use
algorithm from rapidfuzz rather than fuzzywuzzy.
"""
def __init__(
self,
left_on,
right_on,
method="rapidfuzzy_wratio",
threshold=None,
missing_value=0.0,
label=None,
):
super(rapidfuzzy_wratio_comparer, self).__init__(left_on, right_on, label=label)
self.method = method
self.threshold = threshold
self.missing_value = missing_value
def _compute_vectorized(self, s_left, s_right):
if self.method == "rapidfuzzy_wratio":
str_sim_alg = rapidfuzzy_wratio
elif self.method == "rapidfuzzy_partial_ratio":
str_sim_alg = rapidfuzzy_partialratio
elif self.method == "rapidfuzzy_partial_ratio_alignment":
str_sim_alg = rapidfuzzy_partialratioalignment
elif self.method == "rapidfuzzy_get_src_start_pos":
str_sim_alg = rapidfuzzy_get_src_start_pos
else:
raise ValueError("The algorithm '{}' is not known.".format(self.method))
c = str_sim_alg(s_left, s_right)
if self.threshold is not None:
c = c.where((c < self.threshold) | (pd.isnull(c)), other=1.0)
c = c.where((c >= self.threshold) | (pd.isnull(c)), other=0.0)
c = _fillna(c, self.missing_value)
return c
def rapidfuzzy_wratio(s1, s2):
"""Apply rapidfuzz wratio to compare two pandas series"""
conc = pd.Series(list(zip(s1, s2)))
def fuzzy_apply(x):
try:
# divide by 100 to make comparable with levenshtein etc
return (fuzz.WRatio(x[0], x[1])) / 100
except Exception as err:
if pd.isnull(x[0]) or pd.isnull(x[1]):
return np.nan
else:
raise err
return conc.apply(fuzzy_apply)
def rapidfuzzy_partialratio(s1, s2):
"""Apply rapidfuzz partial_ratio to compare two pandas series"""
conc = pd.Series(list(zip(s1, s2)))
def fuzzy_apply(x):
try:
# divide by 100 to make comparable with levenshtein etc
return (fuzz.partial_ratio(x[0], x[1])) / 100
except Exception as err:
if pd.isnull(x[0]) or pd.isnull(x[1]):
return np.nan
else:
raise err
return conc.apply(fuzzy_apply)
def rapidfuzzy_partialratioalignment(s1, s2):
"""Apply rapidfuzz partial_ratio_alignment to compare two pandas series"""
conc = pd.Series(list(zip(s1, s2)))
def fuzzy_apply(x):
try:
calc = fuzz.partial_ratio_alignment(x[0], x[1])
alignment_dist = calc.dest_end - calc.dest_start
# divide by 100 to make comparable with levenshtein etc
return alignment_dist
except Exception as err:
if pd.isnull(x[0]) or pd.isnull(x[1]):
return np.nan
else:
raise err
return conc.apply(fuzzy_apply)
def rapidfuzzy_get_src_start_pos(s1, s2):
"""Apply rapidfuzz partial_ratio_alignment to compare two pandas series"""
conc = pd.Series(list(zip(s1, s2)))
def fuzzy_apply(x):
try:
calc = fuzz.partial_ratio_alignment(x[0], x[1])
return calc.src_start
except Exception as err:
if pd.isnull(x[0]) or pd.isnull(x[1]):
return np.nan
else:
raise err
return conc.apply(fuzzy_apply)
def calc_dist(coords: gpd.GeoSeries):
"""Calculate distance between coordinates. Returns distance.
Parameters
----------
coords: `gpd.GeoSeries`
`gpd.GeoSeries` containing geometry data
Returns
-------
mean_dist: int
Mean distance between 2 or more points in `coords`.
"""
np.seterr(all="ignore")
mean_dist = spatial.distance.pdist(np.array(list(zip(coords.x, coords.y)))).mean()
return mean_dist
def flatten(arg: str | int | list):
"""Flatten list-like objects; if not list just yield `arg`."""
if not isinstance(arg, list):
yield arg
else:
for sub in arg:
yield from flatten(sub)
def validate_pandas_read_csv_kwargs(file_path, csv_params):
"""Validate keyword arguments for `pd.read_csv()`
Parameters
----------
file_path: str
Path to csv-like file.
csv_params: dict
Dictionary of keyword arguments to pass to `pd.read_csv()`.
"""
sig = signature(pd.read_csv)
sig.bind(file_path, **csv_params)
def validate_pandas_excel_kwargs(file_path, excel_params):
"""Validate keyword arguments for `pd.read_excel()`
Parameters
----------
file_path: str
Path to csv-like file.
excel_params: dict
Dictionary of keyword arguments to pass to `pd.read_excel()`.
"""
sig = signature(pd.read_excel)
sig.bind(file_path, **excel_params)
def validate_pandas_to_csv_kwargs(file_path, csv_params):
"""Validate keyword arguments for pandas `to_csv()`
Parameters
----------
file_path: str
Path to csv-like file.
csv_params: dict
Dictionary of keyword arguments to pass to pandas `to_csv()`.
"""
df = pd.DataFrame()
sig = signature(df.to_csv)
sig.bind(file_path, **csv_params)
def validate_geopandas_read_file_kwargs(file_path, params):
"""Validate keyword arguments for `gpd.read_file()`
Parameters
----------
file_path: str
Path to geometry file, e.g. ShapeFile
params: dict
Dictionary of keyword arguments to pass to `gpd.read_file()`.
"""
sig = signature(gpd.read_file)
sig.bind(file_path, **params)
def get_readlibrary(
file_path,
read_params,
):
"""Get the correct library to read a file
Parameters
----------
file_path: str
Path of file to read
read_params: dict
Dictionary of keyword arguments to pass to read library
Returns
-------
read_library: `pd.read_csv` | `pd.read_excel` | `gpd.read_file`
Appropriate read library to read file at `file_path`
"""
ext = pathlib.Path(file_path).suffix
if ext in [
".txt",
".tsv",
".csv",
]:
validate_pandas_read_csv_kwargs(file_path, read_params)
read_library = pd.read_csv
elif ext in [
".xlsx",
]:
validate_pandas_excel_kwargs(file_path, read_params)
read_library = pd.read_excel
elif ext in [
".geojson",
".shp",
]:
read_library = gpd.read_file
return read_library
def read_file(
file_path,
read_params,
) -> pd.DataFrame | gpd.GeoDataFrame:
"""Reads file at `file_path`, returns data in `pd.DataFrame` or `gpd.DataFrame`
Parameters
----------
file_path: str
Path to file to read
read_params: dict
Dictionary of keyword arguments for reading file.
Returns
-------
data: `pd.DataFrame` | `gpd.GeoDataFrame`
`pd.DataFrame` or `gpd.GeoDataFrame` containing data read from `file_path`.
"""
read_library = get_readlibrary(
file_path,
read_params,
)
data = read_library(file_path, **read_params)
return data
def write_df_to_file(
output_df: pd.DataFrame,
output_path_components: list,
pandas_write_params: dict,
):
"""Writes dataframe (e.g. `pd.DataFrame` or `gpd.GeoDataFrame`) to file.
Parameters
----------
output_df: `pd.DataFrame` or `gpd.GeoDataFrame`
dataframe containing data to write to file.
output_path_components: list
List of path components
pandas_write_params: dict
Dictionary of keyword arguments passed to `pd.to_csv`.
"""
output_file_path = pathlib.Path(*output_path_components)
if not output_file_path.parent.exists():
output_file_path.parent.mkdir(parents=True)
output_df.to_csv(output_file_path, **pandas_write_params)
def add_lkup(
data: pd.DataFrame | gpd.GeoDataFrame,
lkup_file: str,
lkup_params: dict,
left_on: str,
right_on: str,
how: str = "left",
lkup_val: str = "integer",
fields_to_drop: str | list = None,
) -> pd.DataFrame | gpd.GeoDataFrame:
"""Adds lookup values from one dataframe to another dataframe. Returns original dataframe with lookup values added.
Parameters
----------
data: `pd.DataFrame` | `gpd.GeoDataFrame`
`pd.DataFrame` or `gpd.GeoDataFrame` containing data to add lookup to.
lkup_file: str
File path of lookup data
lkup_params: dict
Dictonary of keyword arguments for reading `lkup_file`.
left_on: str
Name of `pd.Series` in `data` to join on.
right_on: str
Name of `pd.Series` in `lkup_data` to join on.
how: str, optional
How to perform join between `data` and lookup data.
fields_to_drop: str | list | None, optional
Specify name of field(s) to drop from dataframe after joining lookup data to `data`.
Returns
-------
new_data: `pd.DataFrame` | `gpd.GeoDataFrame`
`pd.DataFrame` or `gpd.GeoDataFrame` containing original `data` with added lookup values.
"""
read_library = get_readlibrary(
lkup_file,
lkup_params,
)
lkup_data = read_library(lkup_file, **lkup_params)
new_data = pd.merge(
left=data,
right=lkup_data,
left_on=left_on,
right_on=right_on,
how=how,
)
lkup_cols_added = [col for col in lkup_data.columns if col != right_on]
new_data = new_data.dropna(subset=lkup_cols_added)
if lkup_val in ["integer", "float"]:
for col in lkup_cols_added:
new_data[col] = pd.to_numeric(new_data[col], downcast=lkup_val)
if fields_to_drop is not None:
new_data = new_data.drop(columns=fields_to_drop)
return new_data