Process Data
getFilteredData(df, impr_acc=100, cpu_cores=max(1, int(cpu_count() / 2)))
¶
Parallel, two–stage cleansing of raw impression data that
- drops points whose GNSS accuracy (
impression_acc
) exceeds the user-specified threshold, and - removes physically implausible jumps using scikit-mob’s
:pyfunc:
skmob.preprocessing.filtering.filter
(max_speed_kmh=200
by default).
The work is split into load-balanced buckets and processed concurrently
with :pyclass:multiprocessing.Pool
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df
|
DataFrame
|
Point-level impressions with at least the columns
|
required |
impr_acc
|
int
|
Maximum allowed GNSS accuracy in metres. Points with a larger
|
100
|
cpu_cores
|
int
|
Number of CPU cores to devote to multiprocessing. By default, half of the available logical cores (but at least 1). |
max(1, int(cpu_count() / 2))
|
Returns:
Name | Type | Description |
---|---|---|
TrajDataFrame |
TrajDataFrame
|
A scikit-mob |
Example
clean_traj = getFilteredData(raw_df, impr_acc=50, cpu_cores=8) print(clean_traj.shape)
Source code in meowmotion/process_data.py
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 |
|
getLoadBalancedBuckets(tdf, bucket_size)
¶
Partition a user-level DataFrame into bucket_size sub-DataFrames whose total row counts (i.e. number of “impressions”) are as evenly balanced as possible. Each bucket can then be processed in parallel on its own CPU core.
Algorithm¶
- Count the number of rows (“impressions”) for every unique
uid
. - Sort users in descending order of impression count.
- Greedily assign each user to the bucket that currently has the smallest total number of impressions (load-balancing heuristic).
- Build one DataFrame per bucket containing only the rows for the users assigned to that bucket.
- Return the list of non-empty bucket DataFrames.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tdf
|
DataFrame
|
A DataFrame that must contain a |
required |
bucket_size
|
int
|
The desired number of buckets—typically equal to the number of CPU
cores you plan to use with :pyclass: |
required |
Returns:
Type | Description |
---|---|
list
|
list[pd.DataFrame]: A list whose length is ≤ bucket_size. Each element is a DataFrame containing a disjoint subset of users such that the cumulative row counts across buckets are approximately balanced. Empty buckets are omitted. |
Example
buckets = getLoadBalancedBuckets(raw_points_df, bucket_size=8) for i, bucket_df in enumerate(buckets, start=1): ... print(f"Bucket {i}: {len(bucket_df):,} rows " ... f"({bucket_df['uid'].nunique()} users)")
Note
The function is designed for embarrassingly parallel workloads where each user’s data can be processed independently (e.g. feature extraction or filtering).
Source code in meowmotion/process_data.py
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 |
|
readJsonFiles(root, month_file)
¶
Load a month-worth of impression records stored as gzipped JSON-Lines inside a ZIP archive and return them as a tidy DataFrame.
Data-at-Rest Format¶
The function expects the following directory / file structure:
``root/ 2023-01.zip # <- month_file argument 2023-01-01-00.json.gz 2023-01-01-01.json.gz ... 2023-01-31-23.json.gz ```
- Each
.json.gz
file is a JSON-Lines file (one JSON object per line). -
Every JSON object is expected to contain at least these keys:
-
impression_acc
(float) – GNSS accuracy (metres) device_iid_hash
(str) – Anonymised user or device IDimpression_lng
(float) – Longitude in WGS-84impression_lat
(float) – Latitude in WGS-84timestamp
(str/int) – ISO-8601 string or Unix epoch (ms)
The loader iterates through each .json.gz
in the archive, parses every
line, and extracts the subset of fields listed above.
Args:
root (str):
Path to the directory that contains month_file (e.g.
"/data/impressions"
).
month_file (str):
Name of the ZIP archive to read
(e.g. "2023-01.zip"
or "london_2024-06.zip"
).
Returns:
pandas.DataFrame:
Columns → ["impression_acc", "uid", "lng", "lat", "datetime"]
One row per JSON object across all .json.gz
files in the archive.
Example: >>> df = readJsonFiles("/data/impressions", "2023-01.zip") >>> df.head() impression_acc uid lng lat datetime 0 6.5 a1b2c3d4e5f6g7h8 -0.12776 51.50735 2023-01-01T00:00:10Z 1 4.8 h8g7f6e5d4c3b2a1 -0.12800 51.50720 2023-01-01T00:00:11Z ...
Source code in meowmotion/process_data.py
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 |
|
saveFile(path, fname, df)
¶
Write a pandas DataFrame to a CSV file, creating the target directory if it does not already exist.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path
|
str
|
Folder in which to store the file
(e.g. |
required |
fname
|
str
|
Name of the CSV file to create
(e.g. |
required |
df
|
DataFrame
|
The DataFrame to be saved. |
required |
Returns:
Type | Description |
---|---|
None
|
None |
Example
saveFile("outputs", "clean_points.csv", clean_df)
→ file written to outputs/clean_points.csv¶
Source code in meowmotion/process_data.py
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 |
|
spatialJoin(df, shape, lng_col, lat_col, loc_type)
¶
Spatially joins point data (supplied in df) to polygon features (supplied in shape) and appends the polygon’s code and name as new columns that are prefixed with the provided loc_type.
Workflow
- Convert each
(lng_col, lat_col)
pair into a Shapely :class:Point
and wrap df into a GeoDataFrame (CRS = EPSG 4326). - Perform a left, intersects-based spatial join with shape.
- Rename
"geo_code" → f"{loc_type}_geo_code"
and"name" → f"{loc_type}_name"
. - Drop internal join artefacts (
index_right
and the pointgeometry
) and return a plain pandas DataFrame.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df
|
DataFrame
|
Point-level DataFrame containing longitude and latitude columns specified by lng_col and lat_col. |
required |
shape
|
GeoDataFrame
|
Polygon layer with at least the columns
|
required |
lng_col
|
str
|
Name of the longitude column in df. |
required |
lat_col
|
str
|
Name of the latitude column in df. |
required |
loc_type
|
str
|
Prefix for the new columns—commonly |
required |
Returns:
Type | Description |
---|---|
pd.DataFrame: A copy of df with two new columns: |
|
|
|
|
|
Rows that do not intersect any polygon will contain |
|
columns. |
Example
enriched_df = spatialJoin( ... df=trip_points, ... shape=lsoa_gdf, ... lng_col="org_lng", ... lat_col="org_lat", ... loc_type="origin" ... ) enriched_df[["origin_geo_code", "origin_name"]].head()
Source code in meowmotion/process_data.py
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 |
|