|
| 1 | +""" |
| 2 | +Plotting how long it takes to do a complex string replace on a whole column |
| 3 | +with various methods. |
| 4 | +
|
| 5 | +In the dataset, in the `place_of_publication` column, you've got entries like |
| 6 | +these: |
| 7 | +
|
| 8 | +London |
| 9 | +London; Virtue & Yorston |
| 10 | +Oxford |
| 11 | +pp. 40. G. Bryan & Co: Oxford, 1898 |
| 12 | +Plymouth |
| 13 | +pp. 40. W. Cann: Plymouth, [1876?] |
| 14 | +
|
| 15 | +Most of these are just city names, but some have additional and unwanted |
| 16 | +information. For these, you want to detect if it has one of the city names, |
| 17 | +replacing the whole value with just the city name. |
| 18 | +""" |
| 19 | + |
| 20 | +import pandas as pd |
| 21 | +import perfplot |
| 22 | + |
| 23 | +books = pd.read_csv("resources/books.csv") |
| 24 | + |
| 25 | +CITIES = ["London", "Plymouth", "Oxford", "Boston"] |
| 26 | + |
| 27 | + |
| 28 | +def _replace_city(text): |
| 29 | + for city in CITIES: |
| 30 | + if city in text: |
| 31 | + return city |
| 32 | + return text |
| 33 | + |
| 34 | + |
| 35 | +def clean_pub_replace(df): |
| 36 | + col = df["place_of_publication"] |
| 37 | + for city in CITIES: |
| 38 | + col = col.replace(rf".*{city}.*", city, regex=True) |
| 39 | + return col |
| 40 | + |
| 41 | + |
| 42 | +def clean_pub_itertuples(df): |
| 43 | + return [_replace_city(row.place_of_publication) for row in df.itertuples()] |
| 44 | + |
| 45 | + |
| 46 | +def clean_pub_iterrows(df): |
| 47 | + return [ |
| 48 | + _replace_city(row["place_of_publication"]) for _, row in df.iterrows() |
| 49 | + ] |
| 50 | + |
| 51 | + |
| 52 | +def clean_pub_apply(df): |
| 53 | + col = df["place_of_publication"] |
| 54 | + for city in CITIES: |
| 55 | + col = col.apply(lambda val: city if city in val else val) |
| 56 | + return col |
| 57 | + |
| 58 | + |
| 59 | +def clean_pub_list_comp(df): |
| 60 | + return [_replace_city(place) for place in df["place_of_publication"]] |
| 61 | + |
| 62 | + |
| 63 | +def get_books(n): |
| 64 | + books = pd.read_csv("resources/books.csv") |
| 65 | + if n < len(books): |
| 66 | + return books.iloc[:n] |
| 67 | + return pd.concat([books for _ in range((n // len(books)) + 1)]).iloc[:n] |
| 68 | + |
| 69 | + |
| 70 | +plot = perfplot.bench( |
| 71 | + setup=lambda n: get_books(n), |
| 72 | + kernels=[ |
| 73 | + clean_pub_replace, |
| 74 | + clean_pub_itertuples, |
| 75 | + clean_pub_iterrows, |
| 76 | + clean_pub_apply, |
| 77 | + clean_pub_list_comp, |
| 78 | + ], |
| 79 | + labels=["replace", "itertuples", "iterrows", "apply", "list comp"], |
| 80 | + n_range=[i**2 for i in range(1, 40, 2)], |
| 81 | + equality_check=None, |
| 82 | +) |
| 83 | + |
| 84 | +plot.show() |
| 85 | +plot.show(logy=True) |
0 commit comments