This repository has been archived by the owner on Sep 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clean.py
68 lines (50 loc) · 1.88 KB
/
clean.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
import re
import geopandas as gpd
import pandas as pd
def _replace_column_names_with_third_row(df):
columns = df.iloc[2].tolist()
df.columns = columns
return df.drop(index=[0, 1, 2]).reset_index(drop=True)
def clean_dublin_postal_districts(dublin_postal_districts):
return (
dublin_postal_districts.pipe(_replace_column_names_with_third_row)
.assign(
postcodes=lambda df: df["Dublin Postal District"].str.replace(
pat=r""" # Replace all substrings
0 # starting with 0
(?=\d) # followed by a number
""",
repl="", # with an empty string
flags=re.VERBOSE,
)
)
.dropna(how="all")
.drop(columns="Dublin Postal District")
.drop(23) # row number of 'Total'
)
def get_county_dublin(counties):
return (
counties.pipe(_replace_column_names_with_third_row)
.iloc[4:5] # index of 'Dublin County'
.rename(columns={"County": "postcodes"})
.replace({"Dublin County": "Co. Dublin"})
)
def clean_dublin_counties(counties):
return (
counties.pipe(_replace_column_names_with_third_row)
.iloc[4:6] # index of 'Dublin County' & 'Dublin Postal Districts'
.rename(columns={"County": "postcodes"})
.replace({"Dublin County": "Co. Dublin"})
)
def amalgamate_postal_districts(dublin_postcode_boundaries):
dublin_postal_districts = (
dublin_postcode_boundaries.assign(x=0)
.query("`postcodes` != 'Co. Dublin'")
.dissolve("x")
.reset_index(drop=True)
.replace({"Dublin 1": "Dublin Postal Districts"})
)
dublin_postcode_boundaries = pd.concat(
[dublin_postcode_boundaries, dublin_postal_districts]
)
return gpd.GeoDataFrame(dublin_postcode_boundaries).reset_index(drop=True)